← Wszystkie zadaniaJavaScript · Middle
memoize: cache wyników
Napisz funkcję memoize(fn), która zwraca wersję fn z cache: przy ponownym wywołaniu z tymi samymi argumentami wynik pochodzi z cache, a fn nie jest wywoływana.
Argumenty to prymitywy i może ich być kilka. m(1) i m("1") to różne wywołania. Wynik undefined też trzeba cache'ować.
Ctrl+Enter uruchamia testy. Tab robi wcięcie; aby wyjść z edytora klawiaturą, naciśnij Esc, a potem Tab. Kod zapisuje się w tej przeglądarce.
Testy (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);