skip to Main Content

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;
        }
    };
}

2

Answers


  1. 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());
    Login or Signup to reply.
  2. we can do it by checking if there are any arguments passed to the function. If not, then return the total value, so this way we can call the add() without any arguments and get the accumulated value.

    function add(...args) {
      if(!add.total) add.total = 0;
      
      if(!args || args.length === 0) {
        let total = add.total;
        add.total = undefined; // reset once retrieved
        return total;
      }
      
      add.total += args.reduce((sum, v) => sum + v, 0);
      return add;
    }
    
    add(1, 2, 3)(4)(5, 6);
    add(7, 8);
    add(9)(10);
    console.log(add());
    
    add(9)(10);
    console.log(add());
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search