0

I have been learning about spread arguments and I found it rather surprising that when using: cur.func.call(null, ...cur.arg, acc), args) that if you have an empty array no argument is passed to add().

Is it possible to reproduce this without using the ... seen in this line of code cur.func.call(null, ...cur.arg, acc), args)

class Lazy {
  constructor() {
    this.builtUpFuncs = [];
  }

  add(...newArgs) {
  console.info(newArgs)
    this.builtUpFuncs.push({
      func: newArgs[0],
      arg:  typeof newArgs[1] === "undefined"  ? [] : [newArgs[1]],
    });
    return this;
  }

  evaluate(target) {
          return target.map((args) => 
            this.builtUpFuncs.reduce((acc, cur) => 
                cur.func.call(null, ...cur.arg, acc), args)
        );
  }
}

const lazyClass = new Lazy();
    const returnValue =
      lazyClass
        .add(function timesTwo(a) { return a * 2; })
        .add(function plus(a, b) { return a + b; }, 1)
      .evaluate([1, 2, 3]);
      
      console.info(returnValue);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Jamie Hutber
  • 26,790
  • 46
  • 179
  • 291
  • 1
    [`...` is not an operator!](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508) – Felix Kling Jan 16 '18 at 17:42

1 Answers1

2

If you want to avoid the spread syntax, the traditional way is to use apply instead of call:

cur.func.apply(null, cur.arg.concat(acc))

Note that the args part is the second argument to reduce, not this function call.

In either syntax it is normal that if cur.arg is an empty array, the only argument passed is acc.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • "Note that the args part is the second argument to reduce, not this function call." Ye, I realise its plopped down onto the lower line, that was me not returning and using `console` :) Otherwise, the last sentence is the key for me then. – Jamie Hutber Jan 16 '18 at 17:42