-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
bb334e9
commit 6b5cd01
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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)! | ||
} | ||
} |
This file contains 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
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) | ||
}) | ||
}) |