1

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)?

Community
  • 1
  • 1
Brad
  • 359
  • 4
  • 12

1 Answers1

1

I think that the coercion to number you are trying to avoid does not relate to add() function, it is the way '+' operator of Javascript works. Therefore changing this behavior is not an 'easy' task. It could take changing the way javascript parser work.

The simplest workaround I can think of (not sure of course how exactly you are using this function) is to always wrap the result with extra add() call, e.g.:

add(2)(3) + 8; // 13, number

can be wrapped like this:

add( add(2)(3) + 8 ); // function with valueOf = 13

Again, not sure about your exact use case though.

Hero Qu
  • 911
  • 9
  • 10
  • That's actually not a bad idea. I figured it would be limited by the way the `+` operator functions, but wasn't sure if maybe there was a workaround in how the add function interacted with it. This seems like a good possible solution. This is more an interest question simply wondering if it could be done, so I haven't invested much in specific cases outside what was outlined in the example. – Brad Jun 03 '16 at 18:35
  • Glad if it was of some help! As for `+` operator, it doesn't seem to like interacting (just as gold with other chemicals). It patiently waits for operands on the left and right to be evaluated and only then comes up and does what it is trained to do and then disappears :) Kind of. – Hero Qu Jun 03 '16 at 23:20