JustMatthew
JustMatthew

Reputation: 372

How to embed functions into functions in javascript like this?

I've just met with a very interesting task to solve, but I can't do it myself.

Make a function which do the following input!

console.log(foo(4)(5)(6)); // output: 120

The solution is not this:

function foo(number1,number2,number3){
  return number1 * number2 * number3;
}

In theory it has to use nested functions.

Upvotes: 0

Views: 91

Answers (6)

Suren Srapyan
Suren Srapyan

Reputation: 68665

It is called currying. You need to return function which it's case returns a function which returns the total. Here we also use a term called closure.

function foo(a){
  return function(b)  {
     return function(c){
       return a * b * c;
     }
   } 
}

console.log(foo(4)(5)(6));

With ES6 syntax

var foo = a => b => c => a*b*c;

console.log(foo(4)(5)(6));

For infinite levels you can do

function foo(value){
  infinite.total = value;
  
  function infinite(val) {
     infinite.total *= val;
     return infinite;
  }
  
  infinite.toString = function() { return infinite.total; }
  
  return infinite;
  
}

console.log(foo(4)(5)(6)(7));

var total = foo(4)(5)(6)(7);
console.log(total);

But this will output the total in that cases, when toString() is called explicitly or implicitly

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386660

You could use an approach for any length of repeated calls of the function with returning a function and an implementation of toString method.

var foo = function(value) {
    function fn(a) {
        fn.value *= a;
        return fn;
    }
    fn.value = value;
    fn.toString = function () { return fn.value; };
    return fn;
}

console.log(foo(4)(5)(6));
console.log(foo(42));
console.log(foo(42)(44));

Upvotes: 2

Laazo
Laazo

Reputation: 467

Using arrow functions;

var foo = a => b => c => a*b*c;

console.log(foo(4)(5)(6));

Upvotes: 1

Mohd Asim Suhail
Mohd Asim Suhail

Reputation: 2292

Closures in javascript will help you to achieve this.

function foo(a){
  return function(b){
    return function(c){
      return a*b*c;
    }
  }
}

console.log(foo(4)(5)(6)); //will return 120

Upvotes: 1

flux
flux

Reputation: 19

You need nested functions - currying;

console.log(foo(4)(5)(6)); // output: 120


let first = foo(4);
let second = first(5);
let last = second(6);

console.log(last);

function foo(number1,number2,number3){
  return function(number2){
    return function(number3){
      return number1 * number2 * number3;
    }
  }
}

Upvotes: 1

daan.desmedt
daan.desmedt

Reputation: 3820

try with currying:

function foo(number) {
  return function(number2) {
    return function(number3) {
      return number * number2  number3;
    }
  }
}

console.log(foo(5)(6)(7));

https://jsfiddle.net/mv9bm3tL/1/

More information : https://www.sitepoint.com/currying-in-functional-javascript/

Upvotes: 1

Related Questions