Elye
Elye

Reputation: 60081

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},
]

Upvotes: 0

Views: 680

Answers (1)

Jacob
Jacob

Reputation: 78850

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

Upvotes: 1

Related Questions