假如有一个接口getUersById(userId),返回用户信息的json; 要求getUersById能缓存用户信息,即同样的userId请求仅发送一次aj

176 阅读1分钟

const cacheFun = function(fn) { const isCallable = function(fn) { return typeof fn === 'function' || Object.prototype.toString.call(fn) === '[object Function]' } if (!isCallable(fn)) { throw new TypeError('参数必须是函数') } 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 key = args.join('-') cache[key] = cache[key] || fn.apply(fn, arguments) return cache[key] } } const getUersById = cacheFun(function(id) { return 'getUersById-' + id + '-result' })