Skip to content

Commit

Permalink
add cached function
Browse files Browse the repository at this point in the history
  • Loading branch information
JeremyMoeglich committed Sep 11, 2023
1 parent 60838c1 commit ecc8e50
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,18 @@ export function init_array<T, D extends readonly number[]>(
return result as ArrayType<T, D>;
}

const cache = new Map<string, unknown>();
export function cached<T>(func: () => T, key: string): T {
if (cache.has(key)) {
return cache.get(key) as T;
} else {
const result = func();
cache.set(key, result);
return result;
}
}


/**
* Cyclically pairs the elements of a given list.
*
Expand Down
14 changes: 14 additions & 0 deletions src/tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
unthrow,
noop,
fake_use,
cached,
init_array,
maybe_global,
at,
Expand All @@ -37,6 +38,19 @@ it('Pairs', () => {
]);
}, 1000);

it("Cached", () => {
let x = 5;
const impure_function = () => {
x++;
return x;
};
assert.equal(impure_function(), 6);
assert.equal(impure_function(), 7);
assert.equal(cached(() => impure_function(), "key1"), 8);
assert.equal(cached(() => impure_function(), "key1"), 8);
assert.equal(cached(() => impure_function(), "key2"), 9);
})

it('Unthrow', () => {
const f = (x: number) => {
if (x < 0) {
Expand Down

0 comments on commit ecc8e50

Please sign in to comment.