I have the following adding function, which appeared originally here.
add
takes only one argument, but it may do so an 'infinite' number of times through the 'magic' of currying and closures.
function add (a) {
var f = b => add(a + b);
f.valueOf = () => a;
return f;
}
var add4 = add(2)(2);
var add6 = add4(2);
var add10 = add6(2)(2);
var add14 = add10(2)+2;
//var add16 = add14(2); no longer works because of type conversion above.
console.log(+add4, +add6, +add10, add14);
//logs 4, 6, 10, 14
You can see, above, that the function can keep creating functions with new a
values that can go on taking additional arguments. The function can also act as a normal variable for the purpose of math operations, such as var sum = add(x)+y;
.
However, once the type conversion takes place, the sum
from the previous example ceases to be a function and is converted to a number.
Now that the background is out of the way, my questions is this: is there a (relatively easy) way to prevent the type coercion of the add
function while still allowing it to be used in arithmetic operations? Or, in other words, is there a simple way to directly modify the valueOf
(and/or a
values) without adding much boilerplate (preferrably while maintaining the add(x)+y;
structure)?