Last active
February 26, 2017 00:23
-
-
Save nvasilakis/06fb8f7e6fb4dae09eb25f0debef0750 to your computer and use it in GitHub Desktop.
Cool prototype patching
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
function memoize(fun) { | |
// memoize a function with arbitrary arguments | |
var memo = {} | |
var name = fun.name || "anonymous"; | |
return function memoize_fun() { | |
this.name = this.name + "__" + name; | |
var args = arguments; | |
var sargs = JSON.stringify(args); | |
if (memo[sargs]) { | |
return memo[sargs]; | |
} | |
memo[sargs] = fun.apply(this, args); | |
return memo[sargs]; | |
} | |
} | |
function time(fun) { | |
// memoize a function with arbitrary arguments | |
var name = fun.name || "anonymous"; | |
var now = new Date(); | |
return function() { | |
var args = arguments; | |
var res = fun.apply(this, args); | |
console.log("[" + name + "] excecution time: " + (new Date() - now) + "ms"); | |
return res; | |
} | |
} | |
var fib = function(x) { | |
// you need an object so that you call the monkey-patched function | |
return x <= 1 ? x : fib(x - 1) + fib(x - 2); | |
} | |
console.log("fib (42): " + time(fib)(42)) | |
var fib = memoize(fib); | |
console.log("memoize(fib)(42): " + time(fib)(42)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment