With memory function, it can reduce the number of cycles

let memoize = function(fn,resolver){
    console.log('resolver:', resolver);
    let cache = {};
    return function(...args){
        let key = typeof resolver === 'function' ? resolver.apply(this,args) :JSON.stringify(args);
        if(!cache.hasOwnProperty(key)){
            cache[key] = fn.apply(this,args);
        }
        return cache[key];
    };
}

let count = 0; 
let fibonacci = function(n) {
    count++;
    return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}
fibonacci = memoize(fibonacci);
for(let i=0; i<10; i++) {
    console.log(fibonacci(i));
}
console.log('总次数:',count);

 

Guess you like

Origin www.cnblogs.com/seasonxin/p/11570432.html