简体   繁体   中英

Can I store function in key-value pair where the function is the key for JavaScript?

I have a list of functions as below

function max(result, current) {
    if (result > current) return result
    else return current
}

function min(result, current) {
    if (result < current) return result
    else return current
}

function sum(result, current) {
    return result + current
}

function product(result, current) {
    return result * current
}

I can store them in an array as below

const mapOfFunctions = [
    sum,
    product,
    max,
    min,
]

But can I store them as a key-value pair, where the function is the key?

const mapOfFunctions = [
    {sum: 0},
    {product: 1},
    {max: Number.MIN_SAFE_INTEGER},
    {min: Number.MAX_SAFE_INTEGER},
]

Yes. The Map class lets you use any object as a key:

const identities = new Map([
  [sum, 0],
  [product, 1],
  [max, Number.MIN_SAFE_INTEGER],
  [min, Number.MAX_SAFE_INTEGER]
]);

const sumIdentity = identities.get(sum); // 0
const productIdentity = identities.get(product); // 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM