Williammer
6/4/2014 - 11:06 AM

jsPatterns.memorizeFn.js

jsPatterns.memorizeFn.js

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);