Socket
Socket
Sign inDemoInstall

memoize-one

Package Overview
Dependencies
0
Maintainers
1
Versions
35
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    memoize-one

A memoization library which only remembers the latest invokation


Version published
Maintainers
1
Install size
135 kB
Created

Package description

What is memoize-one?

The memoize-one package is a simple and lightweight memoization library designed for memoizing the result of a function based on the latest arguments. It only remembers the latest arguments and result, and it will only recompute the result when the arguments change. This can be particularly useful for optimizing performance in scenarios where expensive function calls are frequently made with the same arguments.

What are memoize-one's main functionalities?

Simple memoization of functions

This feature allows you to create a memoized version of a function that caches the result based on the latest set of arguments it was called with. If the function is called again with the same arguments, the cached result is returned instead of recomputing.

const memoizeOne = require('memoize-one');
const add = (a, b) => a + b;
const memoizedAdd = memoizeOne(add);

console.log(memoizedAdd(1, 2)); // 3
console.log(memoizedAdd(1, 2)); // 3, cached result
console.log(memoizedAdd(2, 2)); // 4, recomputed because arguments changed

Custom equality function

This feature allows you to provide a custom function to compare the equality of arguments. This is useful when you need to memoize a function that takes complex arguments like objects or arrays and the default shallow comparison is not sufficient.

const memoizeOne = require('memoize-one');
const isEqual = (newArgs, lastArgs) => JSON.stringify(newArgs) === JSON.stringify(lastArgs);
const complexFunction = (obj) => {/* complex operation */};
const memoizedComplexFunction = memoizeOne(complexFunction, isEqual);

Other packages similar to memoize-one

Readme

Source

memoizeOne

A memoization library which only remembers the latest invokation

Build Status codecov dependencies SemVer

Rationale

Cache invalidation is hard:

There are only two hard things in Computer Science: cache invalidation and naming things.

Phil Karlton

So keep things simple and just use a cache size of one.

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

Usage

Standard usage

import memoizeOne from 'memoize-one';

const add = (a, b) => a + b;
const memoizedAdd = memoizeOne(add);

memoizedAdd(1, 2); // 3

memoizedAdd(1, 2); // 3
// Add function is not executed: previous result is returned

memoizedAdd(2, 3); // 5
// Add function is called to get new value

memoizedAdd(2, 3); // 5
// Add function is not executed: previous result is returned

memoizedAdd(1, 2); // 3
// Add function is called to get new value.
// While this was previously cached,
// it is not the latest so the cached result is lost

Play with this example

Custom equality function

You can also pass in a custom function for checking the equality of two items.

import memoizeOne from 'memoize-one';
import deepEqual from 'lodash.isEqual';

const identity = x => x;

const defaultMemoization = memoizeOne(identity);
const customMemoization = memoizeOne(identity, deepEqual);

const result1 = defaultMemoization({foo: 'bar'});
const result2 = defaultMemoization({foo: 'bar'});

result1 === result2 // false - difference reference

const result3 = customMemoization({foo: 'bar'});
const result4 = customMemoization({foo: 'bar'});

result3 === result4 // true - arguments are deep equal

Play with this example

Type signature

Here is the expected flow type signature for a custom equality function:

type EqualityFn = (a: any, b: any) => boolean;

Installation

# yarn
yarn add memoize-one

# npm
npm install memoize-one --save

this

memoizeOne 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 event 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, memoizeOne takes into account the current execution context (this) of the memoized function. If this is different to the previous invokation 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. memoizeOne 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.

Code health

Keywords

FAQs

Last updated on 08 Feb 2017

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc