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
You can create a wrapper function (
createAdder
, for example) that wraps your code which stores the total sum. That wrapper function will return youradd
function which you can store in a variable (add
) and then use to get your total output, for example: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.