Created
April 29, 2011 20:06
-
-
Save midu/948939 to your computer and use it in GitHub Desktop.
JavaScript Tip of the Day
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var counter = 0; | |
var n_calls = function () { | |
console.log("This function was called ", ++counter, " times"); | |
}; | |
n_calls(); // This function was called 1 times | |
n_calls(); // This function was called 2 times | |
n_calls(); // This function was called 3 times | |
// evil hacker code: | |
counter = NaN; | |
n_calls(); // This function was called NaN times | |
// NOW WITH CLOSURE: | |
var n_calls = function () { | |
var counter = 0; | |
return function () { | |
console.log("This function was called ", ++counter, " times"); | |
}; | |
}(); | |
n_calls(); // This function was called 1 times | |
n_calls(); // This function was called 2 times | |
n_calls(); // This function was called 3 times | |
// evil hacker code: | |
counter = NaN; | |
n_calls(); // This function was called 4 times | |
// \o/ | |
// Example 2: avoid reevaluation | |
// regular fibo without cache | |
var calls = 0; | |
var fibo = function(n) { | |
++calls; | |
if (n == 0 || n == 1) { return n; } | |
return fibo(n - 1) + fibo(n - 2); | |
} | |
calls = 0; | |
console.log(fibo(10)); // 55 | |
console.log(calls); // 177 | |
calls = 0; | |
console.log(fibo(10)); // 55 | |
console.log(calls); // 177 | |
calls = 0; | |
console.log(fibo(20)); // 6765 | |
console.log(calls); // 21891 | |
// with awesome hawt closure cache | |
var calls = 0; | |
var fibo = function() { | |
var cache = [0, 1]; | |
return function(n) { | |
++calls; | |
if (typeof cache[n] !== 'number') { | |
return (cache[n] = fibo(n - 1) + fibo(n - 2)); | |
} else | |
return cache[n]; | |
}; | |
}(); | |
calls = 0; | |
console.log(fibo(10)); // 55 | |
console.log(calls); // 19 | |
calls = 0; | |
console.log(fibo(10)); // 55 | |
console.log(calls); // 1 | |
// without resetting the env (reloading the page) | |
console.log(fibo(20)); // 6765 | |
console.log(calls); // 21 | |
// resetting the env | |
console.log(fibo(20)); // 6765 | |
console.log(calls); // 21 | |
// resetting the env | |
console.log(fibo(100)); // 354224848179262000000 | |
console.log(calls); // 199 <- 22 more than regular fibo(10) | |
// HOT! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment