[Javascript] Memoization

2021-03-28 18:26

阅读:672

标签:null   script   ring   javascrip   cto   mem   color   return   turn   

const factorial = (n) => (n > 1 ? n * factorial(n - 1) : 1);

const memoize = (fn) => {
  const cache = {};
  return (...args) => {
    const key = JSON.stringify(args);
    return key in cache ? cache[key] : (cache[key] = fn.apply(null, args));
  };
};

const memoizedFactorial = memoize(factorial);

console.log(memoizedFactorial(9, { name: ‘Todd Motto‘ }));
console.log(memoizedFactorial(6));
console.log(memoizedFactorial(9, { name: ‘Todd Motto‘ }));

 

[Javascript] Memoization

标签:null   script   ring   javascrip   cto   mem   color   return   turn   

原文地址:https://www.cnblogs.com/Answer1215/p/13622386.html


评论


亲,登录后才可以留言!