npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

memoize-one-ts

v0.0.1

Published

A memoization library which only remembers the latest invocation. Built with TypeScript and includes decorators.

Downloads

39

Readme

memoize-one

A memoization library that only caches the result of the most recent arguments. This a fork of Alex Reardon's fantastic memoize-one JavaScript library, but is written in TypeScript and utilizes decorators to better facilitate our Local by Flywheel coding efforts.

Rationale

Unlike other memoization libraries, memoize-one-ts 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. memoize-one-ts 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-ts';

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

Installation

# yarn
yarn add memoize-one-ts

# npm
npm install memoize-one-ts --save

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);
type EqualityFn = (newArgs: any[], oldArgs: any[]) => boolean;

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

The default equality function is a shallow equal check of all arguments (each argument is compared with ===). The default equality function also does not check anything if the length of the arguments changes. You are welcome to decide if you want to return false if the length of the arguments is not equal

const simpleIsEqual: EqualityFn = (
  newArgs: any[],
  lastArgs: any[],
): boolean =>
  newArgs.length === lastArgs.length &&
  newArgs.every(
    (newArg: any, index: number): boolean =>
      shallowEqual(newArg, lastArgs[index]),
  );

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-ts';
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 - difference reference

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

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

this

memoize-one-ts 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-ts 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-ts 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.

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