Skip to content

Instantly share code, notes, and snippets.

@creamidea
Last active July 14, 2022 15:26
Show Gist options
  • Save creamidea/8145035 to your computer and use it in GitHub Desktop.
Save creamidea/8145035 to your computer and use it in GitHub Desktop.
函数式编程当中,缓存技巧叫做「记忆」(memorization),一阶乘函数。
function memorize(f) {
var cache = {};
// 这个函数是什么意思呢
// 就是使用闭包的特性,保留了cache的值
// 这值将间接使用上次调用时产生的值。下面例子中会详细讲解。
return function() {
console.log(cache); // 打印缓存值
// 这里的key就是一个签名档意思,也就是被缓存函数的参数
var key = Array.prototype.join.call(arguments, ',');
// console.log(key)
if (key in cache) return cache[key];
else return cache[key] = f.apply(this, arguments); // 这里是执行函数和缓存其计算值
};
}
// 测试1
function gcd(a, b) {
if (!a || !b) return
var t;
if (a < b) t = b, b = a, a = t;
while(b != 0) t = b, b = a % b, a = t;
return a;
}
var gcdmemo = memorize(gcd);
console.log(gcdmemo(85, 187)); // Object {} 187
console.log(gcdmemo()); // Object {85, 187: 187} undefined
// 从上面可以看到(85, 187)的计算值被缓存了
// 测试2
var factorial = memorize(function(n) {
return (n <= 1) ? 1 : n * factorial(n - 1);
})
console.log(factorial(5)) // Object {} * 5 120
console.log(factorial(4)) // Object {1: 1, 2: 2, 3: 6, 4: 24, 5: 120} 24
// 可以看到每一次的factorial的值都被记录了,这样就加速下次计算了。
// 而且注意到factorial(5)计算了5次,但是factorial(4)只进行了一步。
// 其实感觉是一种表格技术(随便说说)
// 也可以使用下面的测试
// function factorial2(n) {
// return (n <= 1) ? 1 : n * factorial(n - 1);
// }
// var factorialmemo = memorize(factorial2)
// console.log(factorialmemo(5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment