22
2020
05

手动实现缓存方法

function memoize(fn) {

  const cache = {};

  return function (param) {

    if (cache[param]) {

      console.log('cached');

      return cache[param];

    } else {

      let result = fn(param);

      cache[param] = result;

      console.log(`not cached`);

      return result;

    }

  }

}


const toUpper = (str ="")=> str.toUpperCase();


const toUpperMemoized = memoize(toUpper);


toUpperMemoized("abcdef");

toUpperMemoized("abcdef");

这个缓存函数适用于接受一个参数。我们需要改变下,让它接受多个参数。


const slice = Array.prototype.slice;

function memoize(fn) {

  const cache = {};

  return (...args) => {

    const params = slice.call(args);

    console.log(params);

    if (cache[params]) {

      console.log('cached');

      return cache[params];

    } else {

      let result = fn(...args);

      cache[params] = result;

      console.log(`not cached`);

      return result;

    }

  }

}

const makeFullName = (fName, lName) => `${fName} ${lName}`;

const reduceAdd = (numbers, startingValue = 0) =>

 numbers.reduce((total, cur) => total + cur, startingValue);


const memoizedMakeFullName = memoize(makeFullName);

const memoizedReduceAdd = memoize(reduceAdd);


memoizedMakeFullName("Marko", "Polo");

memoizedMakeFullName("Marko", "Polo");


memoizedReduceAdd([1, 2, 3, 4, 5], 5);

memoizedReduceAdd([1, 2, 3, 4, 5], 5);

« 上一篇 下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。