Last active
December 19, 2015 15:09
-
-
Save fidel-karsto/5974305 to your computer and use it in GitHub Desktop.
cache a function and its return value
This file contains 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 memo = function (fn) { | |
var cache = {}, | |
toType = function(obj) { | |
return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase(); | |
}; | |
return function () { | |
var key = [].join.call(arguments, '§') + '§'; | |
if (!(key in cache)) { | |
cache[key] = fn.apply(this, arguments); | |
} | |
if (toType(cache[key]) === "array") { | |
return cache[key].slice(); | |
} else { | |
return cache[key]; | |
} | |
}; | |
}; | |
/* | |
// ### Side effect ### | |
var foo = 1; | |
function bar(baz) { | |
return baz + foo; | |
} | |
var cached = memo(foo); | |
cached(1); //2 | |
foo += 1; | |
cached(1); //2 | |
*/ | |
/* | |
function loop(count) { | |
var x = 0; | |
while(count > 0){ | |
x++; | |
count--; | |
} | |
console.log("done x=%o", x); | |
return x; | |
} | |
function loop2(count) { | |
var x = 0; | |
while(count > 0){ | |
x += 2; | |
count--; | |
} | |
console.log("done x2=%o", x); | |
return x; | |
} | |
var cachedLoop = memo(loop); | |
var cachedLoop2 = memo(loop2); | |
var loopCount = 10e6; | |
console.time("1st run"); | |
console.log("loops: %o",cachedLoop(loopCount)); | |
console.timeEnd("1st run"); | |
console.log("----------"); | |
console.time("2nd run"); | |
console.log("loops: %o", cachedLoop(loopCount)); | |
console.timeEnd("2nd run"); | |
console.log("----------"); | |
console.time("3nd run - different args"); | |
console.log("loops: %o", cachedLoop(loopCount + 1)); | |
console.timeEnd("3nd run - different args"); | |
console.log("----------"); | |
console.time("4th run"); | |
console.log("loops: %o", cachedLoop2(loopCount)); | |
console.timeEnd("4th run"); | |
console.log("----------"); | |
console.time("5th run"); | |
console.log("loops: %o", cachedLoop2(loopCount)); | |
console.timeEnd("5th run"); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment