memoize-last
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

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:

import { memoizeLast } from 'memoize-last';

... or like this:

import memoizeLast from 'memoize-last';

Basic

const addMemoized = memoizeLast((a, b) => {
  console.log('Ran it!');
  return a + b;
});
 
addMemoized(1, 2); // 3
// Log: Ran it!
 
addMemoized(1, 2); // 3
// ... crickets..
 
addMemoized(0, 3); // 3
// Log: Ran it!

With React (and class fields)

class List extends Component {
  state = {
    people: []
  };
 
  sortListByName = memoizeLast(people =>
    people.sort((a, b) => (< b ? -1 : 1))
  );
 
  render() {
    return (
      <ul>
        {this.sortListByName(this.props.people).map(person => (
          <li key={person.id}>{name}</li>
        ))}
      </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)
  }
}

(class fields)

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 = memoizeLast(user => user.name);
const person = { name: 'Adam' };
 
getName(person); // Adam
 
person.name = 'Eva';
 
getName(person); // 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.

Readme

Keywords

none

Package Sidebar

Install

npm i memoize-last

Weekly Downloads

1

Version

1.1.0

License

MIT

Last publish

Collaborators

  • nbostrom