← 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ć.

Testy (5)

  1. const f = fn((n) => n * 2);
    const m = memoize(f);
    expect(m(2)).toBe(4);
    expect(m(2)).toBe(4);
    expect(f).toHaveBeenCalledTimes(1);
  2. const f = fn((a, b) => a + b);
    const m = memoize(f);
    m(1, 2); m(1, 2); m(2, 1);
    expect(f).toHaveBeenCalledTimes(2);
  3. const f = fn((x) => typeof x);
    const m = memoize(f);
    expect(m(1)).toBe('number');
    expect(m('1')).toBe('string');
    expect(f).toHaveBeenCalledTimes(2);
  4. const f = fn(() => undefined);
    const m = memoize(f);
    m(5); m(5);
    expect(f).toHaveBeenCalledTimes(1);
  5. const a = memoize((x) => x + 1);
    const b = memoize((x) => x + 2);
    expect(a(1)).toBe(2);
    expect(b(1)).toBe(3);