Taken from Secrets of the JavaScript Ninja, Listing 5.14 passes the num argument of isPrime to a memoized function, I assumed the num argument would be visible in #1, and not in #2, But it's actually The other way around!
Function.prototype.memoized = function(key){
this._values = this._values || {};
return this._values[key] !== undefined ?
this._values[key] :
this._values[key] = this.apply(this, arguments);
};
Function.prototype.memoize = function() {
var fn = this; //#1
console.log(Array.prototype.slice.call(arguments)); // Prints []
return function(){ //#2
console.log(Array.prototype.slice.call(arguments)); //Prints [17]
return fn.memoized.apply(fn, arguments);
};
};
var isPrime = (function(num) {
var prime = num != 1;
for (var i = 2; i < num; i++) {
if (num % i == 0) {
prime = false;
break;
}
}
return prime;
}).memoize();
assert(isPrime(17), "17 is prime"); //#3
How is it possible that the num argument (17 in this case) is visible only in the inner closure (#2) and not in the wrapping memoize function? I don't understand at which point the memoize() call passes the num argument to the closure in #2.
PS. To reiterate, and complement the Question above: Why can't I see the num argument in #1?
Thank you.
Because #2 is the function that is assigned to isPrime. And you pass 17 to isPrime. On the other hand, you call .memoize (#1) without passing any arguments to it:
(function() { ... }).memoize()
// ^^ no arguments
I don't understand at which point the memoize() call passes the num argument to the closure in #2.
It doesn't. memoize returns a new function and it's that function to which the argument is passed.
Because at that point, the anonymous function has't been called.
What you are doing is calling memoize, with your anonymous function as the this value and no arguments (hence the empty arguments array)
memoize then returns a function, which basically checks "has this function already been called with this argument", and either return the previous value if so, or calls the function and stores its return value if not.
What this means is that your function is only called when you actually do isPrime(17), and at that point your are inside the function where it says return function() {...} and that's where you can see your argument.
Related
I am new to programming and trying to understand callback functions and functions in general. This program compares 2 values passed in the functions(using callback) and return true/false to us.
function func1(param1, callback) {
return callback(param1);
}
function func2(param2) {
return function(param3) {
return param3 > param2;
}
}
var functionResult = func1(10, func2(9));
console.log(functionResult); // prints - true
Question - In this program above, how does the return function inside the func2 function, return the value directly to us, without being invoked? I thought in this line var functionResult = func1(10, func2(9)); func2(9) will return only the text
function(param3) {
return param3 > param2;
}
and then I would have to invoke it again with ().
how does the return function inside the func2 function, return the value directly to us, without being invoked?
It is invoked. func1 invokes it here:
callback(param1)
func2(9) will return only the text ...
That's not text, that's actually a function (object). It is passed to func1 which in turn calls it and returns its return value.
and then I would have to invoke it again with ().
Yes, which, again, is what func1 does:
callback(param1)
Lets take things apart:
var functionResult = func1(10, func2(9));
is the same as
var func2Result = func2(9);
var functionResult = func1(10, func2Result);
Since we know what func1 does, we can replace the call to it with it's implementation. 10 is passed as param1 and func2Result is passed as callback, so the code becomes:
var func2Result = func2(9);
var functionResult = func2Result(10); // callback(param1);
Now you should be able to see that the return value of func2 is actually called.
I'm struggling with an example of js memoization found on a book, here's the code:
Function.prototype.memoized = function(key){
this._values = this._values || {};
return this._values[key] !== undefined ? this._values[key] : this._values[key] = this.apply(this, arguments);
}
here's a fiddle with a complete example
what I don't really get is how this piece of code works and what it does, in particular the apply part:
return this._values[key] !== undefined ? this._values[key] : this._values[key] = this.apply(this, arguments);
I know and understand how apply works
The apply() method calls a function with a given this value and arguments provided as an array
suppose that this._values[key] is equal to undefined, then the returned value will be this.apply(this, arguments): does this code re-launch the memoized function? I've tried to add some logs inside the function to see how many times the function is called, but it seems it's been launched only once..
Can anyone please give me a hint? It's probably a dummy question, please be patient, thanks
Let's use a simple example, fibonacci numbers.
function fib(n) {
if (n < 2) return 1;
return fib.memoized(n-1) + fib.memoized(n-2);
}
Here we can see that the memoized method is applied on the fib function, i.e. your this keyword refers to the fib function. It does not relaunch the memoized function, but "launches" the function on which it was called. However, it does call it with this set to the function itself, which does not make any sense. Better:
Function.prototype.memoized = function(key){
if (!this._values)
this._values = {};
if (key in this._values)
return this._values[key];
else
return this._values[key] = this.apply(null, arguments);
// pass null here: ^^^^
}
Even better would be if memoized would return a closure:
Function.prototype.memoized = function(v) {
var fn = this, // the function on which "memoized" was called
values = v || {};
return function(key) {
if (key in values)
return values[key];
else
return values[key] = fn.apply(this, arguments);
}
}
var fib = function(n) {
if (n < 2) return 1;
return fib(n-1) + fib(n-2);
}.memoized();
// or even
var fib = function(n) { return fib(n-1) + fib(n-2) }.memoized({0:1, 1:1});
Notes
Since you are attaching memoized to the Function.prototype, you can invoke this memoized on some other function only. Like in your example
isPrime.memoized(5)
Since you are invoking memoized on a function, the this will be referring to the function on which the memoized is invoked. So, in this case, this refers to isPrime.
Actual explanation
this._values = this._values || {};
This line makes sure that the isPrime has got an attribute with the name _values and it should have an empty object, if it is not there already.
this._values[key] !== undefined
This check is to make sure that we have been already called with key or not. If the value is not undefined, then return this._values[key].
Otherwise,
this._values[key] = this.apply(this, arguments)
store the result of calling this.apply(this, arguments) in this._values[key] and return it. Now the important part.
this.apply(this, arguments)
It is straight forward. arguments is an array like object. So, If you have actually called isPrime like this isPrime(1, 2, 3, 4), arguments will have {'0': 1, '1': 2, '2': 3, '3': 4}. Now that we are inside memoized, we need to invoke isPrime as it was intended to be invoked. So, this.apply(this, arguments) is done. Function.prototype.apply, tries to spread the array like object passed as the second parameter, while invoking the function.
Since bind is not a cross browser (old ones) function , there is a polyfill for it : ( from John Resig's book)
/*1*/ Function.prototype.bind = function ()
/*2*/ {
/*3*/ var fn = this,
/*4*/ args = Array.prototype.slice.call(arguments),
/*5*/ object = args.shift();
/*6*/ return function ()
/*7*/ {
/*8*/ return fn.apply(object,
/*9*/ args.concat(Array.prototype.slice.call(arguments)));
/*10*/ };
/*11*/ };
But I don't understand why do we need arguments at line #9.
I mean :
If I have this object :
var foo = {
x: 3
}
And I have this function :
var bar = function(p,b){
console.log(this.x+' '+p+' '+b);
}
So , if I want bar to run in the foo context , with parameters - All I need to do is :
var boundFunc = bar.bind(foo,1,2)
boundFunc ()...
So When I run var.bind(foo,1,2) the arguments is [object Object],1,2.
Those arguments are saved at line #4.
Great.
Now , the bind function returns its own closured function :
function ()
{
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
}
Question
Why do we need arguments here ? it seems that they are for something like :
var boundFunc = bar.bind(foo,1,2)
boundFunc (more1,more2....) //<----- ??
Am I missing something ?
Oonce I set the first var boundFunc = bar.bind(foo,1,2) , I already declared the parameters. why do we need them twice ?
There are two places you can pass in arguments to the bound function:
1) When you call bind (the first arguments). These are always applied to the bound function when it is called.
2) When you call the bound function (the second arguments). These are the "more1, more2" that you mention. These change depending on what is provided when the bound argument is called.
Line 9 is combining the original bound arguments with the supplied extra arguments.
I guess the concept you might be confused about is that you don't have to bind ALL arguments initially - you can bind just the context object, or you can bind the first one argument as well but have callers of the bound function supply the rest. For example:
function sum() {
var _sum = 0
for (var i = 0; i < arguments.length ; i++) {
_sum += arguments[i];
}
return _sum;
}
var sum_plus_two = sum.bind({},2);
sum_plus_two(5,7) == 14;
.bind also serves as partial application solution. Event handlers might be the best example:
var handler = function(data, event) { };
element.addEventListener('click', handler.bind(null, someData));
If the arguments from the actual function call wouldn't be passed on, you couldn't access the event object.
function asArray(quasiArray, start) {
var result = [];
for (var i = (start || 0); i < quasiArray.length; i++)
result.push(quasiArray[i]);
return result;
}
function partial(func) {
var fixedArgs = asArray(arguments, 1);
return function(){
return func.apply(null, fixedArgs.concat(asArray(arguments)));
};
}
function compose(func1, func2) {
return function() {
return func1(func2.apply(null, arguments));
};
}
var isUndefined = partial(op["==="], undefined);
var isDefined = compose(op["!"], isUndefined);
show(isDefined(Math.PI));
show(isDefined(Math.PIE));
Why can't the function compose simply return:
func1(func2);
and give the proper output. I thought the partial function which is stored in the variable isUndefined already returns func.apply(null, [fixed, arguments])
var op = {
"+": function(a, b){return a + b;},
"==": function(a, b){return a == b;},
"===": function(a, b){return a === b;},
"!": function(a){return !a;}
/* and so on */
};
Both partial and compose are higher-order functions.
isUndefined will return a function that, when invoked, will invoke the originally passed function with the original arguments plus any new arguments passed at invocation.
To answer your question, you'd be calling apply on the function returned from partial which will in turn, call apply on the function originally passed to partial.
You want compose to return a function that when called, will return the result of calling the first function passed the second function as an argument (with the second function passed the arguments passed to the compose invocation). If compose returned func1(func2), then you'd assign the result of the invocation to the variable isDefined.
EDIT:
Now that we have op, let's try to decompose this:
var isUndefined = partial(op["==="], undefined);
this is equivalent to
var isUndefined = partial(function(a, b){return a === b;}, undefined);
isUndefined is assigned a function that, when called, will call the function passed as the first argument to partial, passing in undefined as the first argument to that function call, followed by the arguments passed to the function isUndefined i.e.
partial(function(a, b){return a === b;}, undefined /* this will become 'a' when isUndefined is invoked */)(argumentForisUndefined /* this will become 'b' when isUndefined is invoked */);
isDefined composes isUndefined with another function that negates the result of isUndefined.
var isDefined = compose(op["!"], isUndefined);
is equivalent to
var isDefined = compose(function(a){return !a;}, isUndefined);
which is equivalent to (renamed variables for clarity)
var isDefined = compose(
function(a){return !a;},
partial( /* partial function becomes 'a' passed to first function */
function(b, c) {
return b === c;
},
undefined /* undefined becomes 'b' passed to partial */
)
)(argumentForisDefined /* argumentForisDefined becomes 'c' passed to partial */);
If we look at what we have so far and substituting for readability, boils down to a function that takes an argument and compares it to undefined, negates the result and returns a boolean
var isDefined = function (b) { return !undefined === b; }
So lets simply dissect it. Assuming we have this compose function:
function compose(func1, func2) {
return func1(func2.apply(null, arguments));
}
What will happen when you use it like this?
a = compose(function(){console.log(1)}, function(){console.log(2)});
The second function would be call immediately outputting 2, and straight afterwards the first function will be called outputting 1. a will be undefined, because the first function does not return anything.
What you want combine to do, is to return a new function, that combines the two other functions and that you can call at will.
Doing the above all on the original compose, will return a new function, that, when you call it with a() will output 2 and then 1.
I understand calling function(1) but not function(1)(2), how does it work?
also possible for function(1)(2)(3)(4) too?
In this case you are supposing that function(1) returns a function, than you are calling this new, anonymous function with an argument of 2.
See this example:
function sum(a) {
return function(b) {
return a+b;
}
}
// Usage:
window.alert(sum(5)(3)); // shows 8
var add2 = sum(2);
window.alert(add2(5)); // shows 7
window.alert(typeof(add2)); // shows 'function'
Here we create a function sum that takes one argument. Inside the function sum, we create an anonymous function that takes another argument. This anonymous function is returned as the result of executing sum.
Note that this anonymous function is a great example of what we call closure. A closure is a function that keeps the context in which it was created. In this case, it will keep the value of the variable a inside it, as did the example function add2. If we create many closures, they are independent as you can see:
var add3 = sum(3);
var add4 = sum(4);
window.alert(add3(3)); // shows 6
window.alert(add4(3)); // shows 7
Furthermore, they won't get "confused" if you have similarly named local variables:
var a = "Hello, world";
function multiply(a) {
return function(b) {
return a * b;
}
}
window.alert(multiply(6)(7)); // shows 42
var twoTimes = multiply(2);
window.alert(typeof(twoTimes));
window.alert(twoTimes(5));
So, after a call to sum(2) or multiply(2) the result is not a number, nor a string, but is a function. This is a characteristic of functional languages -- languages in which functions can be passed as parameters and returned as results of other functions.
You have a function that returns a function:
function f(n) {
return function(x) {
return n + x;
};
}
When you call f(1) you get a reference to a function back. You can either store the reference in a variable and call it:
var fx = f(1);
var result = fx(2);
Or you can call it directly:
var result = f(1)(2);
To get a function that returns a function that returns a function that returns a function, you just have to repeat the process:
function f(n) {
return function(x) {
return function(y) {
return function(z) {
return n + x + y + z;
}
}
};
}
If your function returns a function, you can call that too.
x = f(1)(2)
is equivalent to:
f2 = f(1)
x = f2(2)
The parenthesis indicate invocation of a function (you "call" it). If you have
<anything>()
It means that the value of anything is a callable value. Imagine the following function:
function add(n1) {
return function add_second(n2) {
return n1+n2
}
}
You can then invoke it as add(1)(2) which would equal 3. You can naturally extend this as much as you want.