Skip to content

memo

Memoize a function

307 bytes

Usage

Wrap a function with memo to get a function back that automagically returns values that have already been calculated.

import * as _ from 'radashi'
const timestamp = _.memo(() => Date.now())
const now = timestamp()
const later = timestamp()
now === later // => true

Expiration

You can optionally pass a ttl (time to live) that will expire memoized results. In versions prior to version 10, ttl had a value of 300 milliseconds if not specified.

import * as _ from 'radashi'
const timestamp = _.memo(() => Date.now(), {
ttl: 1000, // milliseconds
})
const now = timestamp()
const later = timestamp()
await _.sleep(2000)
const muchLater = timestamp()
now === later // => true
now === muchLater // => false

Key Function

You can optionally customize how values are stored when memoized.

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