Simple memoization function that only remembers the last result.
Equality checks are made using referential equality checks, so this lib would fit well into React applications.
Installation
With yarn:
yarn add memoize-last
With npm:
npm install memoize-last
Usage
It exports both a named export and a default one, so you import it either like this:
;
... or like this:
;
Basic
const addMemoized = ; ; // 3// Log: Ran it! ; // 3// ... crickets.. ; // 3// Log: Ran it!
With React (and class fields)
state = people: ; sortListByName = ; { return <ul> this </ul> ; // MY GOD THATS FAST (the second time around if list didnt change // .. and moon is full... and, well this list is empty, but you get the idea) }
Note on referential equality
Note that this library only does referential equality checks. This means that if you mutate an object and pass the same object again, the passed function may not get called and you wont receive the expected result:
const getName = ;const person = name: 'Adam' ; ; // Adam personname = 'Eva'; ; // Adam <-- oops!
If you need deep checks you should check out the memoization function of underscore or lodash instead.
Typescript
This module is written in typescript and therefor provides types out of the box.
It should pass through the type of the wrapped function, so the type of
memoizeLast(myFunc)
should be the same as myFunc
.