javascriptclosurescurrying

Currying function which retains value using closure


I was asked in an interview to write a currying function which retains value using closure(Javascript). Example: add(1, 2, 3)(4)(5, 6); add(7, 8); add(9)(10); add(); Output of above line of code should be 55 after execution of last add function.

So it should be like- add(1, 2, 3)(4)(5, 6); -> 21 add(7, 8); -> 21(previous value) + 15 -> 36 add(9)(10); -> 36(previous value) + 19 -> 55 add(); -> 55(final output)

could someone please me with the solution? Thanks in advance.

I tried the below approach but not able to retain the value as on every call finalOutput variable gets reinitialised to 0. I tried wrapping it in another function to leverage the closure feature but didn't work.

function add(...arg) {
    let finalOutput = 0;
    if (arg.length === 0) {
        return finalOutput;
    }
    return function (...newArg) {
        if (newArg.length) {
        let argsArr = [...arg, ...newArg];
        finalOutput = argsArr.reduce((acc, currentValue) => {
            return acc + currentValue;
        });
        return add(finalOutput);
        } else {
          return finalOutput;
        }
    };
}

Solution

  • You can create a wrapper function (createAdder, for example) that wraps your code which stores the total sum. That wrapper function will return your add function which you can store in a variable (add) and then use to get your total output, for example:

    function createAdder() {
      let finalOutput = 0;
      return function add(...args) {
        if(args.length === 0)
          return finalOutput;
        
        finalOutput += args.reduce((sum, v) => sum + v, 0);
        return add;
      }
    }
    
    
    const add = createAdder();
    
    add(1, 2, 3)(4)(5, 6);
    add(7, 8);
    add(9)(10);
    console.log(add());