1

The same function summ :

summ(7)(3)(5) must equal 15

and

summ(7)(3)+5 must equal 15

and

summ(7)(3) must equal 10

How to make it possible?

hear whtti
  • 21
  • 3
  • `summ` should return something that can optionally be treated as either a function or a number...? – deceze Jun 28 '16 at 10:10

1 Answers1

3

You can use toString/valueOf method to treat result as a value.

function sum(a) {
  chain.valueOf = function() {return a;}
  return chain;

  function chain(s) {
    a += s;
    return chain;
  };
}

sum(7)(3)(5)  == 15  // true
sum(7)(3) + 5 == 15  // true
+sum(7)(3)(5)        // 15
vp_arth
  • 14,461
  • 4
  • 37
  • 66
  • 1
    `valueOf` makes more sense for non-string values, though – Bergi Jun 28 '16 at 10:26
  • I've edited my question. Help, please. Thank you! – hear whtti Jun 28 '16 at 10:51
  • @hearwhtti, what's wrong? it works. It must to return a function to possibility of next call, but `valueOf` allow us to interpret this function as a value. `+sum(7)(3) === 10`, `sum(7)(3) == 10`. What more you need? – vp_arth Jun 28 '16 at 10:57
  • I'm studying, can you, please, explain: why 'sum(7)(3) === 10' returns false and '+sum(7)(3) == 10' returns true. What is purpose of '+' ? – hear whtti Jun 28 '16 at 11:40
  • `+val` is like `0+val` just type conversion to numeric. `sum(5)` result has `function` type. It's why strict equality `===` fails. After type conversion with `+sum(5)` both side has `number` type and same value. – vp_arth Jun 28 '16 at 12:28