+ 1
Sum with arbitrary amount of brackets. Why does it work?!?!?
I’ve found this in js tutorial and I really can’t understand how it works. function sum (a) { let currentSum = 0; function func (b) { currentSum += b; return func; } func[Symbol.toPrimitive] = function () { return currentSum; } return func; } console.log(sum(5)(10)) // 15 console.log(sum(5)(10)(15)) // 30 I understand that here we use closure. What I really can’t understand why we need to transform function to primitive? Please explain me. I really start to feel panic bec I can’t understand that thing
3 Respuestas
+ 3
max In normal circumstances, we cannot perform add or multiply operations on object or function.
Eg. 2+obj1 + obj2 or 3*fn1+fn2 (errors)
However string can be auto type convert to number by default
eg. +str1
Number also can be auto type convert to string when, eg. "a" + 100
For function and object, we can perform type conversion too, by using Symbol.toPrimitive.
Symbol.toPrimitive allows object to be acted like primitive var, it also controls the output of the primitive value.
More information check out the code, I have added more examples to show how does Symbol.toPrimitive alter the object/function in type conversion.
https://code.sololearn.com/W0iY3PK3mLBP/?ref=app
Since you understand closure, I would not explain the closure part of your code here.
+ 1
still dont understand why do we need to transform the function? I know how symbol.toprimitive works and i know that functions are objects so we if we want to do some calc with them we need to transform them. But I cant figure out why should we transform the func in this ex??
0
If you try to remove
func[Symbol.toPrimitive] = function () {
return currentSum;
}
you would get unprotected function code output on console.log due to function code cannot transform to primitive value.
This code
func[Symbol.toPrimitive] = function () {
return currentSum;
}
enables console.log to output a primitive value in the final output value instead of function code, when it was not called by function (n).
This is a way how closure protects its own function codes being exploited to external, while letting function implementation set as public
Study this example:
https://code.sololearn.com/WcieGEM2PV9G/?ref=app