Big update!Introducing GitHub Bot Commands. Learn more →
Socket
Log inDemoInstall

memoize-one

Package Overview
Dependencies
0
Maintainers
1
Versions
35
Issues
File Explorer

Advanced tools

memoize-one

A memoization library which only remembers the latest invocation

    6.0.0latest
    Github

Version published
Maintainers
1
Weekly downloads
9,237,553
increased by12.83%

Weekly downloads

Changelog

Source

6.0.0

At a glance

🧹 New .clear() function to remove the current memoization cache 🏋️‍♀️ Stronger types 🥰 Improved documentation

This release is a major, but there are no behaviour or API changes. The major is to reflect that some of the TypeScript types have been tightened which might cause some peoples TypeScript builds to break.

PSA: memoize-one will soon™️ be dropping ie11 support More details

New: Cache releasing with .clear() 🧹

A .clear() property is now added to memoized functions to allow you to clear it's memoization cache

This is helpful if you want to:

  • Release memory
  • Allow the underlying function to be called again without having to change arguments
import memoizeOne from 'memoize-one'; function add(a: number, b: number): number { return a + b; } const memoizedAdd = memoizeOne(add); // first call - not memoized const first = memoizedAdd(1, 2); // second call - cache hit (underlying function not called) const second = memoizedAdd(1, 2); // 👋 clearing memoization cache memoizedAdd.clear(); // third call - not memoized (cache was cleared) const third = memoizedAdd(1, 2);

Improved: memoized function type

There are no API changes to memoize-one, this is merely a typing improvement

Our previous type for a memoized function was simple:

Previous

export declare type EqualityFn = (newArgs: any[], lastArgs: any[]) => boolean; declare function memoizeOne<ResultFn extends (this: any, ...newArgs: any[]) => ReturnType<ResultFn>>(resultFn: ResultFn, isEqual?: EqualityFn): ResultFn;

A memoized function claimed to be the same type (ResultFn) as the original function. This was not true, as memoize-one does not copy of any existing object properties on the original function (TFunc)

Updated

export declare type MemoizedFn<TFunc extends (this: any, ...args: any[]) => any> = { clear: () => void; (this: ThisParameterType<TFunc>, ...args: Parameters<TFunc>): ReturnType<TFunc>; }; declare function memoizeOne<TFunc extends (this: any, ...newArgs: any[]) => any>( resultFn: TFunc, isEqual?: EqualityFn<TFunc>, ): MemoizedFn<TFunc>;

A memoized function returns the same callable signature as the original function (TFunc → was ResultFn), but it makes it clear that no function object properties on the original function (TFunc) are being carried forward. The memoized function also now includes a .clear() function object property

If you want to continue to use the old types where the memoized function is the same type as the function being memoized, you can achieve this by casting the type of your memoized function:

function add(first: number, second: number): number { return first + second; } // a type that matches our add function type AddFn = (first: number, second: number) => number; // type of memoized will be MemoizedFn<typeof add> const memoized = memoize(add); // option 1 const memoized: typeof add = memoize(add); // option 2 const memoized: AddFn = memoize(add); // option 3 const memoized = memoize(add) as typeof add; // option 4 const memoized = memoize(add) as AddFn;

This type change has been labelled as a patch (fix) as the previous type was not correct. However, you could consider it a major given that the new type is narrower than before

Improved: equality function type

There are no API changes to equality functions, this is merely a typing improvement

Previous

export type EqualityFn = (newArgs: any[], lastArgs: any[]) => boolean;

Current

export type EqualityFn<TFunc extends (...args: any[]) => any> = ( newArgs: Parameters<TFunc>, lastArgs: Parameters<TFunc>, ) => boolean;

This looks a little scary, but it is pretty neat! It means that you can dramatically improve the type safety of your custom equality functions if you want to.

If you are not using a custom equality function

No changes for you!

If you are using a custom equality function

Most people will not be impacted!

This type tightening allows you to be a lot stricter with the shape of your functions passed in as equality functions. If you are using generic equality functions such as lodash.isequal their types are loose and there is nothing you will need to do. But if you want to write more efficient and typesafe equality functions, you are in for a treat.

An example of what things looked like in 5.x

import memoize, { EqualityFn } from "memoize-one"; type Person = { id: string; name: string; }; function invite(person: Person) { // This could do something fancy, but just keeping things basic console.log("invited:", person.name); } // Yuck, we don't know anything about the args // Note: don't really need the `EqualityFn` type as it is just: // `type EqualityFn = (newArgs: any[], lastArgs: any[]) => boolean;` const isEqual: EqualityFn = (newArgs: any[], lastArgs: any[]): boolean => { // Yuck #2: we have to cast here // We would also be creating a bug if isEqual is used on a function // that has no arguments const first = newArgs[0] as Person; const second = lastArgs[0] as Person; return first.id === second.id; }; const memoized = memoize(invite, isEqual); const alex: Person = { name: "Alex", id: "11111" }; memoized(alex); // Won't do anything as `alex` has the same id as the last `alex` memoized(alex);

→ You can play with this example on codesandbox.io

The same example in 6.x

import memoize, { EqualityFn } from "memoize-one"; type Person = { id: string; name: string; }; function invite(person: Person) { console.log("invited:", person.name); } // Yum: we know that newArgs + lastArgs are the tuple `[Person]` const isEqual: EqualityFn<typeof invite> = ([first], [second]): boolean => { return first.id === second.id; }; const memoized = memoize(invite, isEqual); const alex: Person = { name: "Alex", id: "11111" }; memoized(alex); // Won't do anything as `alex` has the same id as the last `alex` memoized(alex); // When declared inline, our isEqual function has the correct types inferred const inferred = memoize(invite, function isEqual([first], [second]): boolean { return first.id === second.id; });

→ You can play with this example on codesandbox.io

There are a few cases where this could cause your TypeScript types to start failing, so this change has been listed as a major

Improved: Documentation

  • Cleanup and audit of examples
  • Added documentation for .clear()
  • Added documentation about function properties and the .length property
  • Updated performance benchmarks

Internal code health

Thanks ❤️

Thanks so much to the following people who helped make this release possible:

  • @danieldelcore
  • @oriSomething
  • @TrySound
  • @theKashey
  • @AndrewOCC
  • @wbinnssmith
  • @bolasblack
  • @OliverJAsh
  • @Offirmo

Catch you next time,

  • @alexreardon 🤘

Readme

Source

memoize-one

A memoization library that only caches the result of the most recent arguments.

npm types minzip Downloads per month

Rationale

Unlike other memoization libraries, memoize-one only remembers the latest arguments and result. No need to worry about cache busting mechanisms such as maxAge, maxSize, exclusions and so on, which can be prone to memory leaks. A function memoized with memoize-one simply remembers the last arguments, and if the memoized function is next called with the same arguments then it returns the previous result.

For working with promises, @Kikobeats has built async-memoize-one.

Usage

// memoize-one uses the default import import memoizeOne from 'memoize-one'; function add(a, b) { return a + b; } const memoizedAdd = memoizeOne(add); memoizedAdd(1, 2); // add function: is called // [new value returned: 3] memoizedAdd(1, 2); // add function: not called // [cached result is returned: 3] memoizedAdd(2, 3); // add function: is called // [new value returned: 5] memoizedAdd(2, 3); // add function: not called // [cached result is returned: 5] memoizedAdd(1, 2); // add function: is called // [new value returned: 3] // 👇 // While the result of `add(1, 2)` was previously cached // `(1, 2)` was not the *latest* arguments (the last call was `(2, 3)`) // so the previous cached result of `(1, 3)` was lost

Installation

# yarn yarn add memoize-one # npm npm install memoize-one --save

Function argument equality

By default, we apply our own fast and relatively naive equality function to determine whether the arguments provided to your function are equal. You can see the full code here: are-inputs-equal.ts.

(By default) function arguments are considered equal if:

  1. there is same amount of arguments
  2. each new argument has strict equality (===) with the previous argument
  3. [special case] if two arguments are not === and they are both NaN then the two arguments are treated as equal

What this looks like in practice:

import memoizeOne from 'memoize-one'; // add all numbers provided to the function const add = (...args = []) => args.reduce((current, value) => { return current + value; }, 0); const memoizedAdd = memoizeOne(add);
  1. there is same amount of arguments
memoizedAdd(1, 2); // the amount of arguments has changed, so underlying add function is called memoizedAdd(1, 2, 3);
  1. new arguments have strict equality (===) with the previous argument
memoizedAdd(1, 2); // each argument is `===` to the last argument, so cache is used memoizedAdd(1, 2); // second argument has changed, so add function is called again memoizedAdd(1, 3); // the first value is not `===` to the previous first value (1 !== 3) // so add function is called again memoizedAdd(3, 1);
  1. [special case] if the arguments are not === and they are both NaN then the argument is treated as equal
memoizedAdd(NaN); // Even though NaN !== NaN these arguments are // treated as equal as they are both `NaN` memoizedAdd(NaN);

Custom equality function

You can also pass in a custom function for checking the equality of two sets of arguments

const memoized = memoizeOne(fn, isEqual);

An equality function should return true if the arguments are equal. If true is returned then the wrapped function will not be called.

Tip: A custom equality function needs to compare Arrays. The newArgs array will be a new reference every time so a simple newArgs === lastArgs will always return false.

Equality functions are not called if the this context of the function has changed (see below).

Here is an example that uses a lodash.isEqual deep equal equality check

lodash.isequal correctly handles deep comparing two arrays

import memoizeOne from 'memoize-one'; import isDeepEqual from 'lodash.isequal'; const identity = (x) => x; const shallowMemoized = memoizeOne(identity); const deepMemoized = memoizeOne(identity, isDeepEqual); const result1 = shallowMemoized({ foo: 'bar' }); const result2 = shallowMemoized({ foo: 'bar' }); result1 === result2; // false - different object reference const result3 = deepMemoized({ foo: 'bar' }); const result4 = deepMemoized({ foo: 'bar' }); result3 === result4; // true - arguments are deep equal

The equality function needs to conform to the EqualityFn type:

// TFunc is the function being memoized type EqualityFn<TFunc extends (...args: any[]) => any> = ( newArgs: Parameters<TFunc>, lastArgs: Parameters<TFunc>, ) => boolean; // You can import this type import type { EqualityFn } from 'memoize-one';

The EqualityFn type allows you to create equality functions that are extremely typesafe. You are welcome to provide your own less type safe equality functions.

Here are some examples of equality functions which are ordered by most type safe, to least type safe:

Example equality function types

// the function we are going to memoize function add(first: number, second: number): number { return first + second; } // Some options for our equality function // ↑ stronger types // ↓ weaker types // ✅ exact parameters of `add` { const isEqual = function (first: Parameters<typeof add>, second: Parameters<typeof add>) { return true; }; expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); } // ✅ tuple of the correct types { const isEqual = function (first: [number, number], second: [number, number]) { return true; }; expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); } // ❌ tuple of incorrect types { const isEqual = function (first: [number, string], second: [number, number]) { return true; }; expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>(); } // ✅ array of the correct types { const isEqual = function (first: number[], second: number[]) { return true; }; expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); } // ❌ array of incorrect types { const isEqual = function (first: string[], second: number[]) { return true; }; expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>(); } // ✅ tuple of 'unknown' { const isEqual = function (first: [unknown, unknown], second: [unknown, unknown]) { return true; }; expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); } // ❌ tuple of 'unknown' of incorrect length { const isEqual = function (first: [unknown, unknown, unknown], second: [unknown, unknown]) { return true; }; expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>(); } // ✅ array of 'unknown' { const isEqual = function (first: unknown[], second: unknown[]) { return true; }; expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); } // ✅ spread of 'unknown' { const isEqual = function (...first: unknown[]) { return !!first; }; expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); } // ✅ tuple of 'any' { const isEqual = function (first: [any, any], second: [any, any]) { return true; }; expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); } // ❌ tuple of 'any' or incorrect size { const isEqual = function (first: [any, any, any], second: [any, any]) { return true; }; expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>(); } // ✅ array of 'any' { const isEqual = function (first: any[], second: any[]) { return true; }; expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); } // ✅ two arguments of type any { const isEqual = function (first: any, second: any) { return true; }; expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); } // ✅ a single argument of type any { const isEqual = function (first: any) { return true; }; expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); } // ✅ spread of any type { const isEqual = function (...first: any[]) { return true; }; expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); }

this

memoize-one correctly respects this control

This library takes special care to maintain, and allow control over the the this context for both the original function being memoized as well as the returned memoized function. Both the original function and the memoized function's this context respect all the this controlling techniques:

  • new bindings (new)
  • explicit binding (call, apply, bind);
  • implicit binding (call site: obj.foo());
  • default binding (window or undefined in strict mode);
  • fat arrow binding (binding to lexical this)
  • ignored this (pass null as this to explicit binding)

Changes to this is considered an argument change

Changes to the running context (this) of a function can result in the function returning a different value even though its arguments have stayed the same:

function getA() { return this.a; } const temp1 = { a: 20, }; const temp2 = { a: 30, }; getA.call(temp1); // 20 getA.call(temp2); // 30

Therefore, in order to prevent against unexpected results, memoize-one takes into account the current execution context (this) of the memoized function. If this is different to the previous invocation then it is considered a change in argument. further discussion.

Generally this will be of no impact if you are not explicity controlling the this context of functions you want to memoize with explicit binding or implicit binding. memoize-One will detect when you are manipulating this and will then consider the this context as an argument. If this changes, it will re-execute the original function even if the arguments have not changed.

Clearing the memoization cache

A .clear() property is added to memoized functions to allow you to clear it's memoization cache.

This is helpful if you want to:

  • Release memory
  • Allow the underlying function to be called again without having to change arguments
import memoizeOne from 'memoize-one'; function add(a: number, b: number): number { return a + b; } const memoizedAdd = memoizeOne(add); // first call - not memoized const first = memoizedAdd(1, 2); // second call - cache hit (underlying function not called) const second = memoizedAdd(1, 2); // 👋 clearing memoization cache memoizedAdd.clear(); // third call - not memoized (cache was cleared) const third = memoizedAdd(1, 2);

When your result function throws

There is no caching when your result function throws

If your result function throws then the memoized function will also throw. The throw will not break the memoized functions existing argument cache. It means the memoized function will pretend like it was never called with arguments that made it throw.

const canThrow = (name: string) => { console.log('called'); if (name === 'throw') { throw new Error(name); } return { name }; }; const memoized = memoizeOne(canThrow); const value1 = memoized('Alex'); // console.log => 'called' const value2 = memoized('Alex'); // result function not called console.log(value1 === value2); // console.log => true try { memoized('throw'); // console.log => 'called' } catch (e) { firstError = e; } try { memoized('throw'); // console.log => 'called' // the result function was called again even though it was called twice // with the 'throw' string } catch (e) { secondError = e; } console.log(firstError !== secondError); const value3 = memoized('Alex'); // result function not called as the original memoization cache has not been busted console.log(value1 === value3); // console.log => true

Function properties

Functions memoized with memoize-one do not preserve any properties on the function object.

This behaviour correctly reflected in the TypeScript types

import memoizeOne from 'memoize-one'; function add(a, b) { return a + b; } add.hello = 'hi'; console.log(typeof add.hello); // string const memoized = memoizeOne(add); // hello property on the `add` was not preserved console.log(typeof memoized.hello); // undefined

If you feel strongly that memoize-one should preserve function properties, please raise an issue. This decision was made in order to keep memoize-one as light as possible.

For now, the .length property of a function is not preserved on the memoized function

import memoizeOne from 'memoize-one'; function add(a, b) { return a + b; } console.log(add.length); // 2 const memoized = memoizeOne(add); console.log(memoized.length); // 0

There is no (great) way to correctly set the .length property of the memoized function while also supporting ie11. Once we remove ie11 support then we will set the .length property of the memoized function to match the original function

→ discussion.

Memoized function type

The resulting function you get back from memoize-one has almost the same type as the function that you are memoizing

declare type MemoizedFn<TFunc extends (this: any, ...args: any[]) => any> = { clear: () => void; (this: ThisParameterType<TFunc>, ...args: Parameters<TFunc>): ReturnType<TFunc>; };
  • the same call signature as the function being memoized
  • a .clear() function property added
  • other function object properties on TFunc as not carried over

You are welcome to use the MemoizedFn generic directly from memoize-one if you like:

import memoize, { MemoizedFn } from 'memoize-one'; import isDeepEqual from 'lodash.isequal'; import { expectTypeOf } from 'expect-type'; // Takes any function: TFunc, and returns a Memoized<TFunc> function withDeepEqual<TFunc extends (...args: any[]) => any>(fn: TFunc): MemoizedFn<TFunc> { return memoize(fn, isDeepEqual); } function add(first: number, second: number): number { return first + second; } const memoized = withDeepEqual(add); expectTypeOf<typeof memoized>().toEqualTypeOf<MemoizedFn<typeof add>>();

In this specific example, this type would have been correctly inferred too

import memoize, { MemoizedFn } from 'memoize-one'; import isDeepEqual from 'lodash.isequal'; import { expectTypeOf } from 'expect-type'; // return type of MemoizedFn<TFunc> is inferred function withDeepEqual<TFunc extends (...args: any[]) => any>(fn: TFunc) { return memoize(fn, isDeepEqual); } function add(first: number, second: number): number { return first + second; } const memoized = withDeepEqual(add); // type test still passes expectTypeOf<typeof memoized>().toEqualTypeOf<MemoizedFn<typeof add>>();

Performance 🚀

Tiny

memoize-one is super lightweight at min minified and minzip gzipped. (1KB = 1,024 Bytes)

Extremely fast

memoize-one performs better or on par with than other popular memoization libraries for the purpose of remembering the latest invocation.

The comparisons are not exhaustive and are primarily to show that memoize-one accomplishes remembering the latest invocation really fast. There is variability between runs. The benchmarks do not take into account the differences in feature sets, library sizes, parse time, and so on.

Expand for results

node version 16.11.1

You can run this test in the repo by:

  1. Add "type": "module" to the package.json (why is things so hard)
  2. Run yarn perf:library-comparison

no arguments

PositionLibraryOperations per second
1memoize-one80,112,981
2moize72,885,631
3memoizee35,550,009
4mem (JSON.stringify strategy)4,610,532
5lodash.memoize (JSON.stringify key resolver)3,708,945
6no memoization505
7fast-memoize504

single primitive argument

PositionLibraryOperations per second
1fast-memoize45,482,711
2moize34,810,659
3memoize-one29,030,828
4memoizee23,467,065
5mem (JSON.stringify strategy)3,985,223
6lodash.memoize (JSON.stringify key resolver)3,369,297
7no memoization507

single complex argument

PositionLibraryOperations per second
1moize27,660,856
2memoize-one22,407,916
3memoizee19,546,835
4mem (JSON.stringify strategy)2,068,038
5lodash.memoize (JSON.stringify key resolver)1,911,335
6fast-memoize1,633,855
7no memoization504

multiple primitive arguments

PositionLibraryOperations per second
1moize22,366,497
2memoize-one17,241,995
3memoizee9,789,442
4mem (JSON.stringify strategy)3,065,328
5lodash.memoize (JSON.stringify key resolver)2,663,599
6fast-memoize1,219,548
7no memoization504

multiple complex arguments

PositionLibraryOperations per second
1moize21,788,081
2memoize-one17,321,248
3memoizee9,595,420
4lodash.memoize (JSON.stringify key resolver)873,283
5mem (JSON.stringify strategy)850,779
6fast-memoize687,863
7no memoization504

multiple complex arguments (spreading arguments)

PositionLibraryOperations per second
1moize21,701,537
2memoizee19,463,942
3memoize-one17,027,544
4lodash.memoize (JSON.stringify key resolver)887,816
5mem (JSON.stringify strategy)849,244
6fast-memoize691,512
7no memoization504

Code health 👍

  • Tested with all built in JavaScript types
  • Written in Typescript
  • Correct typing for Typescript and flow type systems
  • No dependencies

Keywords

FAQs

What is memoize-one?

A memoization library which only remembers the latest invocation

Is memoize-one popular?

The npm package memoize-one receives a total of 8,817,526 weekly downloads. As such, memoize-one popularity was classified as popular.

Is memoize-one well maintained?

We found that memoize-one demonstrated a not healthy version release cadence and project activity because the last version was released a year ago.It has 1 open source maintainer collaborating on the project.

Last updated on 20 Oct 2021

Did you know?

Socket installs a Github app to automatically flag issues on every pull request and report the health of your dependencies. Find out what is inside your node modules and prevent malicious activity before you update the dependencies.

Install Socket
Socket[email protected]

Product

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc