hash-memoize

Higher-order function abstraction providing input-output memoization of arbitrary functions

Usage no npm install needed!

<script type="module">
  import hashMemoize from 'https://cdn.skypack.dev/hash-memoize';
</script>

README

hash-memoize

npm version Build Status Coverage Status

Higher-order function abstraction providing input-output memoization of arbitrary functions

Overview

hash-memoize is a higher-order function that takes any arbitrary function as input and memoizes (input, output) pairs. Function return values are cached in an internal object keyed by a unique hash of the passed function arguments.

In practice, this means that any function wrapped with hash-memoize will only ever be invoked once for a given set of arguments; future calls with the same set of arguments will return a cached value. This can significantly speed up code that makes repeated calls to an expensive function.

hash-memoize is best used in scenarios where:

  • Executing the wrapped function is computationally expensive
  • The wrapped function has no side effects (i.e., deterministically returns the same output for a specified input)
  • The wrapped function is called several times, and inputs are likely to be repeated

API

memoize(func)

func is an arbitrary function to memoize. This will return a function with the same signature as func, i.e. can be invoked with the same arguments and have a return value identical to that of func with those arguments.

Examples

Simple function

const memoize = require('hash-memoize');

const add = (a, b) => a + b;
const addMemoized = memoize(add);

console.log(addMemoized(1, 2));  // Calls `add` internally, returns 3
console.log(addMemoized(1, 2));  // Result for these arguments is cached. Returns 3, without calling `add`
console.log(addMemoized(1, 4));  // This argument set isn't cached; calls `add` internally and returns 5

Recursively defined function

You can use function hoisting to your advantage.

const memoize = require('hash-memoize');

const fibMemoized = memoize(fib);
function fib(n) {
  return (n <= 1) ? n : fibMemoized(n - 1) + fibMemoized(n - 2);
}

console.log(fibMemoized(7));  // 13