How to change a function based on unknown number of arguments in javascript

82 Views Asked by At

Is there any way to add to or manipulate expressions in a returned function?

This is an example for a single argument:

function trackByProp(prop) {
  return function (value) {
    return value[prop];
  };
}

The aim is to extend this function to allow multiple props to be added e.g.

function trackByProp(...props) {
  props.forEach((prop) => {
    //Somehow add value[prop] to the return function???
  });

  return function (value) {
    return; // value[arg1] + value[arg2] + value[argN]
  };
}

Alternatively is there a simpler way to create this function ?

1

There are 1 best solutions below

1
Nicholas Foden On
function trackByProps(...props) {
  return function (value) {
    return props.reduce((result, prop) => result + value[prop], "")
  }
}

Using the properties in the inner function ensures they are available in a closure. similar to the single argument example. Then they can be iterated over each time the inner function is called.