memo
记忆化函数
307 bytes
since v12.1.0
使用方法
用 memo 包装函数以获得一个自动返回已计算值的函数。
import * as _ from "radashi";
const timestamp = _.memo(() => Date.now());
const now = timestamp();const later = timestamp();
now === later; // => true过期时间
您可以选择传递一个 ttl(生存时间)来使记忆化结果过期。在版本 10 之前的版本中,如果未指定,ttl 的值为 300 毫秒。
import * as _ from "radashi";
const timestamp = _.memo(() => Date.now(), { ttl: 1000, // 毫秒});
const now = timestamp();const later = timestamp();
await _.sleep(2000);
const muchLater = timestamp();
now === later; // => truenow === muchLater; // => false键函数
您可以选择自定义记忆化时值的存储方式。
const timestamp = _.memo( ({ group }: { group: string }) => { const ts = Date.now(); return `${ts}::${group}`; }, { key: ({ group }: { group: string }) => group, });
const now = timestamp({ group: "alpha" });const later = timestamp({ group: "alpha" });const beta = timestamp({ group: "beta" });
now === later; // => truebeta === now; // => false