-1

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 ?

DecPK
  • 24,537
  • 6
  • 26
  • 42
Nicholas Foden
  • 156
  • 3
  • 12
  • 1
    `Array.prototype.reduce()` – Andreas Sep 20 '21 at 15:13
  • 2
    [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Sep 20 '21 at 15:13
  • 1
    [How to get a subset of a javascript object's properties](https://stackoverflow.com/q/17781472) then do whatever you want with them? – VLAZ Sep 20 '21 at 15:14
  • @Andreas How would I use reduce() in this situation? It's not possible to just accumulate the value[props] as value isn't know at the time of calling ? Maybe I missed something? – Nicholas Foden Sep 20 '21 at 15:18
  • 1
    @NicholasFoden "*It's not possible to just accumulate the value[props] as value isn't know at the time of calling*" why do you even want to do that *before* the inner function is called? If the code is in the inner function, then you do have `value`. – VLAZ Sep 20 '21 at 15:20
  • What I haven't been able to work out is how to get the multiple lookups into the inner function. – Nicholas Foden Sep 20 '21 at 15:24
  • 1
    `return props.reduce((prop, result) => result + value[prop])` or what ever your `value[arg1] + value[arg2] ...` actually is supposed to be. – Andreas Sep 20 '21 at 15:25
  • thanks @VLAZ your link shows lodash's pick seems to be what I am looking for. I am still interested in learning how I would do it myself. perhaps I will just read the lodash code. – Nicholas Foden Sep 20 '21 at 15:26
  • "*how to get the multiple lookups into the inner function.*" with loop or other iteration? – VLAZ Sep 20 '21 at 15:28

1 Answers1

0
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.

Nicholas Foden
  • 156
  • 3
  • 12
  • 1
    In FP we try to keep functions as simple as possible. Your original function is just fine. If you want to process several properties just `map` over them. –  Sep 21 '21 at 08:41