📅 You're Invited: Meet the Socket team at RSAC (April 28 – May 1).RSVP
Socket
Sign inDemoInstall
Socket

@starryinternet/map-memo

Package Overview
Dependencies
Maintainers
2
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@starryinternet/map-memo

Generic memoization with Map and WeakMap

2.1.2
latest
Source
npm
Version published
Weekly downloads
4.3K
42.37%
Maintainers
2
Weekly downloads
 
Created
Source

map-memo

Build Status

Generic memoization using Map and WeakMap.

Installing

npm install --save @starryinternet/map-memo

What/Why?

Memoization in JavaScript has typically been limited to arguments with primitive values, or by utilizing hacks such as stringifying objects.

By storing arguments using a series of nested cache objects backed by Map and WeakMap, map-memo is able to memoize functions with any argument types.

Example

'use strict';

const memoize = require('@starryinternet/map-memo');

function loop( fn, n ) {
  let v;

  for ( let i = 0; i < n; ++i ) {
    v = fn( i );
  }

  return v;
}

let mem = memoize( loop );

console.log( mem( Math.sqrt, 1e9 ) ); // slow
console.log( mem( Math.sqrt, 1e9 ) ); // fast!

Example with expire time in milliseconds

'use strict';

const memoize = require('@starryinternet/map-memo');

function getRandom() {
  return Math.random();
}

let mem = memoize( getRandom, { ttl: 1000 } );
console.log( mem() );
console.log( mem() ); // Same value as above

setTimeout( function() {
  console.log( mem() ); // Different value
}, 1001 );

Example with asynchronous function

'use strict';

const memoize = require('@starryinternet/map-memo');

function loopAsync( fn, n ) {
  return new Promise( ( resolve, reject ) => {
    let v;

    for ( let i = 0; i < n; ++i ) {
      v = fn( i );
    }

    resolve( v );
  });
}

let mem = memoize( loopAsync );

mem( Math.sqrt, 1e9 ).then( result => {
  console.log( result ); // slow
  mem( Math.sqrt, 1e9 ).then( console.log ); // fast!
});

Keywords

memoize

FAQs

Package last updated on 12 Feb 2020

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