← All tasksJavaScript · Middle
memoize: cache results
Write a function memoize(fn) that returns a cached version of fn: a repeated call with the same arguments returns the cached result without calling fn.
Arguments are primitives, and there can be several. m(1) and m("1") are different calls. An undefined result must be cached too.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (5)
const f = fn((n) => n * 2); const m = memoize(f); expect(m(2)).toBe(4); expect(m(2)).toBe(4); expect(f).toHaveBeenCalledTimes(1);
const f = fn((a, b) => a + b); const m = memoize(f); m(1, 2); m(1, 2); m(2, 1); expect(f).toHaveBeenCalledTimes(2);
const f = fn((x) => typeof x); const m = memoize(f); expect(m(1)).toBe('number'); expect(m('1')).toBe('string'); expect(f).toHaveBeenCalledTimes(2);
const f = fn(() => undefined); const m = memoize(f); m(5); m(5); expect(f).toHaveBeenCalledTimes(1);
const a = memoize((x) => x + 1); const b = memoize((x) => x + 2); expect(a(1)).toBe(2); expect(b(1)).toBe(3);