2.1.1 • Published 7 years ago

map-memo v2.1.1

Weekly downloads
47
License
MIT
Repository
github
Last release
7 years ago

map-memo

Build Status

Generic memoization using Map and WeakMap.


Installing

npm install --save 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('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('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('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!
});
2.1.1

7 years ago

2.1.0

8 years ago

2.0.2

8 years ago

2.0.1

8 years ago

2.0.0

8 years ago

1.0.10

9 years ago

1.0.9

9 years ago

1.0.8

9 years ago

1.0.7

9 years ago

1.0.6

9 years ago

1.0.5

9 years ago

1.0.4

9 years ago

1.0.3

9 years ago

1.0.2

9 years ago

1.0.1

9 years ago

1.0.0

9 years ago