0

I have got a quiz that asks the following question, but Im quite not sure if it is possible to pass multiple variables like that on Javascript functions:

Write a function called "MultiplyBy" which will produce the following outputs when invoked:

console.log(mul(2)(3)(4)); // output : 24 
console.log(mul(4)(3)(4)); // output : 48
Marcelo
  • 784
  • 3
  • 9
  • 30
  • It's definitely possible to do this, but it's kind-of tricky and I don't think there's much of a practical reason for it. – Pointy Apr 01 '18 at 21:42
  • 1
    A function can return another function, which can then be invoked. If you want to do this an arbitrary number of times it is complex but if it is always 3 times then this is relatively easy – Paul S. Apr 01 '18 at 21:43
  • Your question is unclear. What is your question? Are you asking whether this is possible? Yes/No questions are usually considered to be bad questions, also "Is it possible?"-type questions are considered to be bad questions as well. Are you asking us to write the code for you? Then your questions is off-topic as well. It is generally expected to show your code and demonstrate your effort, as well as document what you have tried and what did and didn't work (and why). – Jörg W Mittag Apr 01 '18 at 21:45

1 Answers1

3

You can do it returning functions at each call. The name of this technique is currying.

// For three chained calls
function mul(i) {
  return function(j) {
    return function(k) {
      return i * j * k;
    }
  }
}
console.log('result: ' + mul(2)(3)(4)); // output : 24 
console.log('result: ' + mul(4)(3)(4)); // output : 48

// For an arbitrary number of chained calls, must resort to .toString
function mulN(i) {
  var m = (j) => mulN(i * j);
  m.toString = () => ''+i;
  m.valueOf = () => i; // call .valueOf() at any point to get the current val
  return m;
}
console.log('result: ' + mulN(2));
console.log('result: ' + mulN(2)(3));
console.log('result: ' + mulN(2)(3)(4));
console.log('result: ' + mulN(2)(3)(4)(5));
console.log('result: ' + (mulN(2)(3)(4)(5) == 120)); // true because of .valueOf
acdcjunior
  • 132,397
  • 37
  • 331
  • 304