Last active
November 2, 2018 04:19
-
-
Save yangfch3/b31c53f3dbb7045d07eed9b9f67b3d85 to your computer and use it in GitHub Desktop.
[简易缓存机] 对一些方法/函数传参-返回值进行缓存 #设计模式 #utils
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 对一个对象的方法做缓存 | |
function Memoize(func, obj) { | |
obj = obj || window | |
func = obj[func] | |
let cache = {} | |
return function () { | |
let key = Array.prototype.join.call(arguments, '_') | |
if (!(key in cache)) { | |
// console.log('缓存未命中') | |
cache[key] = func.apply(obj, arguments) | |
} | |
return cache[key] | |
} | |
} | |
// 对 fib 的 fib_demo 添加缓存机制 | |
// fib.fib_memo = Memoize('fib_memo', fib) | |
// 对一个简单的函数进行缓存 | |
function Memoize(func, context) { | |
let cache = {} | |
return function () { | |
let key = Array.prototype.join.call(arguments, '_') | |
if (!(key in cache)) { | |
// console.log('缓存未命中') | |
cache[key] = func.apply(context || null, arguments) | |
} | |
return cache[key] | |
} | |
} | |
/** | |
* 异步函数的缓存器工厂 | |
* @param {Function} fn 需要对结果进行缓存的异步函数 | |
* @param {any} context 函数执行需要绑定的 context | |
* @return {Function} | |
*/ | |
function AsyncMemoize(fn, context) { | |
let cache = {} | |
/** | |
* @return {Promise<any>} | |
* | |
* 不往上级调用者上报错误 | |
* 本身不处理错误,请异步函数自身处理错误 | |
* 发生错误时,any 为 null | |
*/ | |
return async function () { | |
let key = Array.prototype.join.call(arguments, '_') | |
if (!(key in cache)) { | |
// 异步操作,获取数据 | |
let data | |
try { | |
data = await fn.apply(context || null, arguments) | |
} catch (e) { | |
data = null | |
} | |
data && (cache[key] = data) | |
} | |
return cache[key] | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment