原文链接:Javascript纯函数缓存
前言
最近看了gitbook上的一本书,名叫《JS函数式编程指南》,看到了一个之前从未想到的小方法,做个笔记,记录一下。
实现
var memoize = function(fn){
var toStr = Object.prototype.toString;
var isCallable = function (fn) {
return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
}
if (!isCallable(fn)) {
throw new TypeError('memoize: when provided, the first argument must be a function');
}
var cache = {};
return function(){
if (arguments.length < 1) {
throw new TypeError('memoize: arguments cannot be null or undefined');
}
var args = Array.prototype.slice.call(arguments);
var str = args.join('-');
cache[str] = cache[str] || fn.apply(fn, arguments);
return cache[str];
};
};
调用的方式很简单,代码如下:
var sum = memoize(function (a, b) {
console.log('开始相加');
return a + b;
});
可以执行一下,看下效果,下图就是在chrome下执行的结果:
结尾
有很多别人用烂的实现方式,对于我还属于一个新奇的技术,要多学多看,多实践。