memo
记忆化一个函数
基本用法
用memo包装一个函数,得到一个自动返回已计算值的新函数。
import { memo } from 'radash'
const timestamp = memo(() => Date.now())
const now = timestamp()
const later = timestamp()
now === later // => true
过期时间
你可以选择性地传递一个ttl(生存时间)参数,用于设置记忆化结果的过期时间。在版本10之前,如果未指定,ttl的默认值为300毫秒。
import { memo, sleep } from 'radash'
const timestamp = memo(() => Date.now(), {
ttl: 1000 // 毫秒
})
const now = timestamp()
const later = timestamp()
await sleep(2000)
const muchLater = timestamp()
now === later // => true
now === 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 // => true
beta === now // => false
相关内容
- alphabetical 按属性对对象数组进行字母顺序排序 给定一个对象数组和一个用于确定排序属性的回调函数,返回一个按字母顺序排序的新数组
- boil 将列表项缩减为一个项 给定一个项数组,返回在比较条件中获胜的最终项
- cluster 将列表拆分为指定大小的多个列表 给定一个项数组和所需的集群大小(`n`),返回一个数组的数组
- counting 创建一个包含项目出现次数的对象 给定一个对象数组和一个用于确定每个对象应如何标识的标识回调函数
- diff 创建两个数组之间的差异数组 给定两个数组,返回第一个数组中存在但第二个数组中不存在的所有项的数组
- first 获取列表中的第一个项 给定一个项数组,返回第一个项,如果不存在任何项则返回默认值