Last active
August 29, 2015 14:02
-
-
Save Williammer/3dc86607399e5e463ba3 to your computer and use it in GitHub Desktop.
jsPatterns.memorizeFn.js
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
| function mem(f) { | |
| var cache = {}; | |
| return function(){ | |
| var key = arguments.length + Array.prototype.join.call(arguments, ','); | |
| console.log(arguments);//seems like the arguments refers to those in f. No! it refers to those in return function() | |
| if(key in cache) return cache[key]; | |
| else return cache[key] = f.apply(this, arguments); | |
| }; | |
| } | |
| //Euclidean_algorithm - greatest common divisor | |
| function gcd(a,b){ | |
| var t; | |
| if(a<b){ | |
| t=b; b=a; a=t; | |
| } | |
| while(b!=0){ | |
| t=b, b=a%b, a=t; | |
| // test case1: a:7, b:3; a=3, b=4; a=3, b=1; a=1, b=0; | |
| } | |
| return a; | |
| } | |
| var gcdcache = mem(gcd);//closure | |
| var re1 = gcdcache(74,194); | |
| console.log(re1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment