Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

memoize-function

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

memoize-function

A memoization library that caches all results and supports *N* arguments with any type.

  • 1.0.0
  • latest
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

memoize-function

Lint Check Test Check Production Build Typecheck Check

In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again. — Wikipedia

A memoization library that caches all results and supports N arguments with any type.

Installation

npm install memoize-function --save

Usage

const memoizeFunction = require("memoize-function");

const factorial = memoizeFunction((value) => {
  if (value <= 1) {
    return 1;
  }

  return value * factorial(value - 1);
});

factorial(50);
factorial(20); // Value from cache

Custom storage

It is possible to pass a custom storage to be used.

const memoized = memoizeFunction(fn, {
  storage: {
    store: {},
    clear() {
      this.store = {};
    },
    remove(key) {
      delete this.store[key];
    },
    set(key, value) {
      this.store[key] = value;
    },
    get(key) {
      return this.store[key] || null;
    },
  },
});
class Storage {
  store;

  constructor() {
    this.store = {};
  }

  clear() {
    this.store = {};
  }

  remove(key) {
    delete this.store[key];
  }

  get(key) {
    return this.store[key] || null;
  }

  set(key, value) {
    this.store[key] = value;
  }
}

const memoized = memoizeFunction(fn, {
  storage: new Storage(),
});

The custom cache can be a class or an object implementing the following methods:

  • get
  • set
  • clear
  • remove

Custom cache key generator

To use a custom cache key generator:

const generateCacheKey = (...args) =>
  "my_custom_key_for_each_function_argument";

const memoized = memoizeFunction(fn, {
  generateCacheKey,
});

Keywords

FAQs

Package last updated on 22 May 2021

Did you know?

Socket

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
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc