qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!
https://github.com/qappleh/Interview
1.15k stars 96 forks source link

Day359:用递归的方式实现fibonacci(n)函数,输入数字n,输出斐波那契数列第N项数字,并给该函数加入缓存功能,例如 #362

Open qappleh opened 3 years ago

qappleh commented 3 years ago
输入 输出
1 1
2 1
3 2
4 3
5 5
6 8

注:斐波那契数列是指第N项为0,第一项为1,第N项(N>1)= 第N-2项 + 第N-1项的数列

AimWhy commented 3 years ago
function memoize(fn) {
    return new Proxy(fn, {
        cache: new Map(),
        apply(target, thisArg, argsList) {
            let cacheKey = argsList.toString();

            if (!this.cache.has(cacheKey)) {
                this.cache.set(cacheKey, target.apply(thisArg, argsList));
            }

            return this.cache.get(cacheKey);
        }
    });
}

const fibonacci = n => (n <= 2 ? 1 : fibonacci(n-1) + fibonacci(n-2));
const memoFibonacci = memoize(fibonacci);