# 2021.01.26 今天是每日时报陪伴您的第 496 天

[文章] 如何在 JavaScript 里面做缓存:https://www.30secondsofcode.org/blog/s/javascript-memoization (opens new window)

const memoize = fn =>
  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 <= 1 ? 1 : fibonacci(n - 1) + fibonacci(n - 2));
const memoizedFibonacci = memoize(fibonacci);

for (let i = 0; i < 100; i++) fibonacci(30); // ~5000ms
for (let i = 0; i < 100; i++) memoizedFibonacci(30); // ~50ms
Last Updated: 1/26/2021, 11:18:39 AM