The task is to implement a sum function.
The boilerplate code
function sum(num) {
// your code here
}
sum(num) returns a function that remembers the current total, can be called again to add more numbers, and can behave like a number when compared
function inner(next) {
return sum(num + next)
}
Each time the function is called, a new sum call is created and the previous value is not modified. JavaScript tries to convert objects to primitives during comparison. Since the result is a function, JS calls valueOf
inner.valueOf = function () {
return num;
};
Some environments use toString, so adding it to the function makes it more robust
inner.toString = function () {
return String(num);
};
The final code
function inner(next) {
return sum (num + next);
}
inner.valueOf = function () {
return num;
}
inner.toString = function () {
return String(num);
}
return inner;
}
That's all folks!
Top comments (0)