I\'m trying to solve a puzzle, and am at my wit\'s end trying to figure it out.
I\'m supposed to make a function that works like this:
add(1);
Here's a variation using bind:
var add = function _add(a, b) {
var boundAdd = _add.bind(null, a + b);
boundAdd.valueOf = function() {
return a + b;
}
return boundAdd;
}.bind(null, 0);
We're taking advantage of a feature of bind
that lets us set default arguments on the function we're binding to. From the docs:
bind() also accepts leading default arguments to provide to the target function when the bound function is called.
So, _add
acts as a sort of master function which takes two parameters a
and b
. It returns a new function boundAdd
which is created by binding the original _add
function's a
parameter to a + b
; it also has an overridden valueOf
function which returns a + b
(the valueOf
function was explained quite well in @RobG's answer).
To get the initial add
function, we bind
_add
's a
parameter to 0
.
Then, when add(1)
is called, a = 0
(from our initial bind
call) and b = 1
(passed argument). It returns a new function where a = 1
(bound to a + b
).
If we then call that function with (2)
, that will set b = 2
and it'll return a new function where a = 3
.
If we then call that function with (3)
, that will set b = 3
and it'll return a new function where a = 6
.
And so on until valueOf
is called, at which point it'll return a + b
. Which, after add(1)(2)(3)
, would be 3 + 3
.
Thanks for the tip on valueOf()
. This is what works:
function add(n) {
var calc = function(x) {
return add(n + x);
}
calc.valueOf = function() {
return n;
}
return calc;
}
--edit--
Could you please explain how this works? Thanks!
I don't know if I know the correct vocabulary to describe exactly how it works, but I'll attempt to:
Example statement: add(1)(1)
When add(1)
is called, a reference to calc
is returned.
calc
understands what n
is because, in the "mind" of the interpreter, calc
is a function child of add
. When calc
looks for n
and doesn't find it locally, it searches up the scope chain
and finds n
.
So when calc(1)
is called, it returns add(n + x)
. Remember, calc
knows what n
is, and x
is simply the current argument (1)
. The addition is actually done inside of calc
, so it returns add(2)
at this point, which in turn returns another reference to calc
.
Step 2 can repeats every time we have another argument (i.e. (x)
).
When there aren't any arguments left, we are left with just a definition
of calc
. The last calc
is never actually called, because you need a ()
to call a function. At this point, normally the interpreter would return a the function object of calc
. But since I overrode calc.valueOf
it runs that function instead.
When calc.valueOf
runs, it finds the most recent instance of n
in the scope chain, which is the cumulative value of all previous n
's.
I hope that made some sense. I just saw @RobG 's explanation, which is admittedly much better than mine. Read that one if you're confused.
Here's a somewhat streamlined version of @RobG's great answer:
function add(n) {
function calc(x) { return n+=x, calc; }
calc.valueOf = function() { return n; };
return calc;
}
The minor difference is that here calc
just updates n
and then returns itself, rather than returning itself via another call to add
, which puts another frame on the stack.
calc
is thus a pure self-replicating function, returning itself. We can encapsulate the notion of "self replication" with the function
function self_replicate(fn) {
return function x() {
fn.apply(this, arguments);
return x;
};
}
Then add
could be written in a possibly more self-documenting way as
function add(n) {
function update(x) { n += x; }
var calc = self_replicate(update);
calc.valueOf = function() { return n; };
return calc;
}
Note that there is a certain parallelity between this approach to repeatedly calling a function and Array#reduce
. Both are reducing a list of things to a single value. In the case of Array#reduce
the list is an array; in our case the list is parameters on repeated calls. Array#reduce
defines a standard signature for reducer functions, namely
function(prev, cur)
where prev
is the "accumulator" (value so far), cur
is the new value being fed in, and the return value becomes the new value the accumulator. It seems useful to rewrite our implementation to make use of a function with that kind of signature:
function add(n) {
function reducer(prev, cur) { return prev + cur; }
function update(x) { n = reducer(n, x); }
var calc = self_replicate(update);
calc.valueOf = function() { return n; };
return calc;
}
Now we can create a more general way to create self-replication-based reducers based on a reducer function:
function make_repeatedly_callable_function(reducer) {
return function(n) {
function update(x) { n = reducer(n, x); }
var calc = self_replicate(update);
calc.valueOf = function() { return n; };
return calc;
};
}
Now we can create add
as
var add = make_repeatedly_callable_function(function(prev, cur) { return prev + cur; });
add(1)(2);
Actually, Array#reduce
calls the reducer function with third and fourth arguments, namely the index into the array and the array itself. The latter has no meaning here, but it's conceivable we might want something like the third argument to know what "iteration" we're on, which is easy enough to do by just keeping track using a variable i
:
function reduce_by_calling_repeatedly(reducer) {
var i = 0;
return function(n) {
function update(x) { n = reducer( n, x, i++); }
var calc = self_replicate(update);
calc.valueOf = function() { return n; };
return calc;
};
}
There are certain advantages to keeping track of the intermediate parameters the function is being called with (using an array), and then doing the reduce at the end instead of as we go along. For instance, then we could do Array#reduceRight
type things:
function reduce_right_by_calling_repeatedly(reducer, initialValue) {
var array_proto = Array.prototype,
push = array_proto.push,
reduceRight = array_proto.reduceRight;
return function(n) {
var stack=[],
calc = self_replicate(push.bind(stack));
calc.valueOf = reduceRight.bind(stack, reducer, initialValue);
return calc(n);
};
}
Let's try using this approach to build ("extend") objects:
function extend_reducer(prev, cur) {
for (i in cur) {
prev[i] = cur[i];
}
return prev;
}
var extend = reduce_by_calling_repeatedly(extend_reducer);
extend({a: 1})({b: 2})
Unfortunately, this won't work because Object#toValue
is invoked only when JS needs a primitive object. So in this case we need to call toValue
explicitly:
extend({a: 1})({b: 2}).toValue()
To answer "how dow this work". Given:
function add(n) {
function calc(x) {
return add(n + x);
}
calc.valueOf = function() {
return n;
}
return calc;
}
var sum = add(1)(2)(3); // 6
When add is called the first time, it stores the value passed in in a variable called n. It then returns the function calc, which has a closure to n and a special valueOf method (explained later).
This function is then called with a value of 2, so it calls add with the sum of n + x
, wich is 1 + 2
which 3.
So a new version of calc is returned, this time with a closure to n with a value of 3.
This new calc is called with a value of 3, so it calls add with n + x
, which this time is 3 + 3
which is 6
Again add returns a new calc with n set to 6. This last time, calc isn't called again. The returned value is assigned to the variable sum. All of the calc functions have a special valueOf method that replaces the standard one provided by Object.prototype. Normally valueOf would just return the function object, but in this case it will return the value of n.
Now sum can be used in expressions, and if its valueOf method is called it will return 6 (i.e. the value of n held in a closure).
This seems pretty cool, and sum will act a lot like a primitve number, but it's actually a function:
typeof sum == 'function';
So be careful with being strict about testing the type of things:
sum * 2 // 12
sum == 6 // true
sum === 6 // false -- oops!!
This is a very simple approach and it meets the criteria the OP was looking for. Namely, the function is passed an integer, keeps track of that integer, and returns itself as a function. If a parameter is not passed - the function returns the sum of the integers passed to it.
let intArray = [];
function add(int){
if(!int){
return intArray.reduce((prev, curr) => prev + curr)
}
intArray.push(int)
return add
}
If you call this like so:
console.log(add(1)(1)());
it outputs 2.