Skip to content

Commit

Permalink
add memoize function
Browse files Browse the repository at this point in the history
  • Loading branch information
andrej-dyck committed Jan 1, 2024
1 parent bb334e9 commit 6b5cd01
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
14 changes: 14 additions & 0 deletions memoize/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Returns a function that will memoize the return values for arguments of (pure) function f and return those on subsequent calls.
* Note that it only supports functions with exactly 1 argument and the values must be equatable (e.g., objects won't work)
*/
export const memoize = <T, R>(f: (arg: T) => R): (arg: T) => R => {
const values = new Map<T, R>()
return (arg: T) => {
if(!values.has(arg)) {
values.set(arg, f(arg))
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return values.get(arg)!
}
}
38 changes: 38 additions & 0 deletions memoize/memoize.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { describe, expect, test } from 'vitest'
import { memoize } from './index.js'

describe('memoize', () => {

test('delegates to function of first call', () => {
const mf = memoize((n: number) => n * 2)
expect(mf(2)).toEqual(4)
})

test('uses memoized return value on subsequent calls', () => {
let calls = 0
const mf = memoize((n: number) => {
calls++
return n * 2
})

expect(mf(2)).toEqual(4)
expect(mf(2)).toEqual(4)
expect(calls).toEqual(1)
})

test('memorizes return value pre argument', () => {
let calls = 0
const mf = memoize((n: number) => {
calls++
return n * 2
})

expect(mf(2)).toEqual(4)
expect(mf(2)).toEqual(4)

expect(mf(1)).toEqual(2)
expect(mf(1)).toEqual(2)

expect(calls).toEqual(2)
})
})

0 comments on commit 6b5cd01

Please sign in to comment.