├── .eslintrc ├── .gitignore ├── .jshintrc ├── .travis.yml ├── Gruntfile.js ├── License.md ├── README.md ├── lib └── map-memo.js ├── package.json └── test └── test.js /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "extends": "starry" 4 | } 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | coverage/ 4 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "boss": true, 3 | "camelcase": true, 4 | "curly": true, 5 | "eqeqeq": true, 6 | "eqnull": true, 7 | "funcscope": true, 8 | "indent": 2, 9 | "lastsemic": true, 10 | "latedef": true, 11 | "maxlen": 80, 12 | "newcap": true, 13 | "quotmark": "single", 14 | "trailing": true, 15 | "undef": true, 16 | "unused": true, 17 | "esnext": true, 18 | "node": true 19 | } 20 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "6.9.5" 4 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | module.exports = function( grunt ) { 2 | 3 | grunt.initConfig({ 4 | pkg: grunt.file.readJSON('package.json'), 5 | jshint: { 6 | options: { 7 | jshintrc: true 8 | }, 9 | src: [ 'lib/**/*.js' ] 10 | }, 11 | eslint: { 12 | target: [ 'lib/**/*.js' ] 13 | }, 14 | mocha_istanbul: { 15 | test: { 16 | src: 'test/test.js', 17 | options: { 18 | reportFormats: [ 'html' ], 19 | check: { 20 | lines: 100, 21 | statements: 100, 22 | branches: 100, 23 | functions: 100 24 | }, 25 | print: 'detail', 26 | root: 'lib' 27 | } 28 | } 29 | } 30 | }); 31 | 32 | grunt.loadNpmTasks('grunt-contrib-jshint'); 33 | grunt.loadNpmTasks('grunt-eslint'); 34 | grunt.loadNpmTasks('grunt-mocha-istanbul'); 35 | grunt.registerTask( 'default', [ 'jshint', 'eslint', 'mocha_istanbul' ] ); 36 | }; 37 | -------------------------------------------------------------------------------- /License.md: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Starry, Inc. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # map-memo 2 | 3 | [![Build Status](https://travis-ci.org/StarryInternet/map-memo.svg?branch=master)](https://travis-ci.org/StarryInternet/map-memo) 4 | 5 | Generic memoization using `Map` and `WeakMap`. 6 | 7 | --- 8 | 9 | ### Installing 10 | 11 | ``` 12 | npm install --save @starryinternet/map-memo 13 | ``` 14 | 15 | --- 16 | 17 | ### What/Why? 18 | 19 | Memoization in JavaScript has typically been limited to arguments 20 | with primitive values, or by utilizing hacks such as stringifying objects. 21 | 22 | By storing arguments using a series of nested cache objects backed by `Map` 23 | and `WeakMap`, `map-memo` is able to memoize functions with *any* 24 | argument types. 25 | 26 | --- 27 | 28 | ### Example 29 | 30 | ```js 31 | 'use strict'; 32 | 33 | const memoize = require('@starryinternet/map-memo'); 34 | 35 | function loop( fn, n ) { 36 | let v; 37 | 38 | for ( let i = 0; i < n; ++i ) { 39 | v = fn( i ); 40 | } 41 | 42 | return v; 43 | } 44 | 45 | let mem = memoize( loop ); 46 | 47 | console.log( mem( Math.sqrt, 1e9 ) ); // slow 48 | console.log( mem( Math.sqrt, 1e9 ) ); // fast! 49 | ``` 50 | 51 | ### Example with expire time in milliseconds 52 | 53 | ```js 54 | 'use strict'; 55 | 56 | const memoize = require('@starryinternet/map-memo'); 57 | 58 | function getRandom() { 59 | return Math.random(); 60 | } 61 | 62 | let mem = memoize( getRandom, { ttl: 1000 } ); 63 | console.log( mem() ); 64 | console.log( mem() ); // Same value as above 65 | 66 | setTimeout( function() { 67 | console.log( mem() ); // Different value 68 | }, 1001 ); 69 | ``` 70 | 71 | ### Example with asynchronous function 72 | 73 | ```js 74 | 'use strict'; 75 | 76 | const memoize = require('@starryinternet/map-memo'); 77 | 78 | function loopAsync( fn, n ) { 79 | return new Promise( ( resolve, reject ) => { 80 | let v; 81 | 82 | for ( let i = 0; i < n; ++i ) { 83 | v = fn( i ); 84 | } 85 | 86 | resolve( v ); 87 | }); 88 | } 89 | 90 | let mem = memoize( loopAsync ); 91 | 92 | mem( Math.sqrt, 1e9 ).then( result => { 93 | console.log( result ); // slow 94 | mem( Math.sqrt, 1e9 ).then( console.log ); // fast! 95 | }); 96 | ``` 97 | -------------------------------------------------------------------------------- /lib/map-memo.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | class Cache { 4 | 5 | constructor() { 6 | this.map = new Map(); 7 | this.weakmap = new WeakMap(); 8 | } 9 | 10 | // create or retrieve a nested Cache instance based on an arguments object 11 | get( args ) { 12 | return args.reduce( Cache.reducer, this ); 13 | } 14 | 15 | // get a backing store (map/weakmap) based on a given value 16 | store( value ) { 17 | const t = typeof value; 18 | const isObject = ( t === 'object' || t === 'function' ) && value !== null; 19 | return Reflect.get( this, isObject ? 'weakmap' : 'map' ); 20 | } 21 | 22 | static reducer( cache, value ) { 23 | const store = cache.store( value ); 24 | return store.get( value ) || store.set( value, new Cache() ).get( value ); 25 | } 26 | 27 | } 28 | 29 | module.exports = function memoize( fn, { ttl = Infinity } = {} ) { 30 | const cache = new Cache(); 31 | 32 | return function( ...args ) { 33 | // get (or create) a cache item 34 | const item = cache.get( args ); 35 | 36 | if ( item.hasOwnProperty('value') && item.expires >= Date.now() ) { 37 | return item.value; 38 | } 39 | 40 | item.expires = Date.now() + ttl; 41 | return item.value = fn.apply( this, args ); 42 | }; 43 | }; 44 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@starryinternet/map-memo", 3 | "version": "2.1.2", 4 | "description": "Generic memoization with Map and WeakMap", 5 | "author": "Kevin Ennis = 4.0.0" 26 | }, 27 | "devDependencies": { 28 | "eslint-config-starry": "2.0.0", 29 | "eslint-plugin-starry": "2.0.0", 30 | "grunt": "1.0.1", 31 | "grunt-contrib-jshint": "1.0.0", 32 | "grunt-eslint": "18.1.0", 33 | "grunt-mocha-istanbul": "4.0.2", 34 | "istanbul": "0.4.3", 35 | "mocha": "2.5.3" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const assert = require('assert'); 4 | const memoize = require('../lib/map-memo'); 5 | 6 | // sample types 7 | const types = [ 8 | 123, 9 | 'foo', 10 | true, 11 | null, 12 | undefined, 13 | {}, 14 | function() {}, 15 | Symbol('foo') 16 | ]; 17 | 18 | describe( 'memoize', () => { 19 | 20 | it( 'should be a function', () => { 21 | assert.equal( typeof memoize, 'function' ); 22 | }); 23 | 24 | it( 'should return a value', () => { 25 | function sqrt( n ) { 26 | return Math.sqrt( n ); 27 | } 28 | 29 | let mem = memoize( sqrt ); 30 | let result = mem( 9 ); 31 | 32 | assert.equal( result, 3 ); 33 | }); 34 | 35 | // check all cache types 36 | types.forEach( val => { 37 | let type = val === null ? 'null' : typeof val; 38 | 39 | it( 'should cache ' + type, () => { 40 | let calls = 0; 41 | let result; 42 | 43 | function fn() { 44 | calls++; 45 | return ( result = null ); 46 | } 47 | 48 | let mem = memoize( fn ); 49 | 50 | let first = mem( val ); 51 | let second = mem( val ); 52 | 53 | assert.equal( first, result, 'Incorrect result was returned' ); 54 | assert.equal( calls, 1, 'Result was not cached' ); 55 | assert.equal( first, second, 'Cached result is incorrect' ); 56 | }); 57 | }); 58 | 59 | it( 'should cache multiple arguments', () => { 60 | let calls = 0; 61 | let result; 62 | 63 | function fn() { 64 | calls++; 65 | return ( result = {} ); 66 | } 67 | 68 | let mem = memoize( fn ); 69 | 70 | let first = mem( types ); 71 | let second = mem( types ); 72 | 73 | assert.equal( first, result, 'Incorrect result was returned' ); 74 | assert.equal( calls, 1, 'Result was not cached' ); 75 | assert.equal( first, second, 'Cached result is incorrect' ); 76 | }); 77 | 78 | it( 'should not return cached results for mismatched arguments', () => { 79 | let calls = 0; 80 | 81 | function fn() { 82 | calls++; 83 | return {}; 84 | } 85 | 86 | let mem = memoize( fn ); 87 | 88 | let first = mem.apply( null, types ); 89 | let second = mem.apply( null, types.reverse() ); 90 | 91 | assert.equal( calls, 2, 'Function was not called twice' ); 92 | assert.notEqual( first, second, 'Result was cached' ); 93 | }); 94 | 95 | it( 'should cache calls with no args', () => { 96 | let calls = 0; 97 | let result; 98 | 99 | function fn() { 100 | calls++; 101 | return ( result = {} ); 102 | } 103 | 104 | let mem = memoize( fn ); 105 | 106 | let first = mem(); 107 | let second = mem(); 108 | 109 | assert.equal( first, result, 'Incorrect result was returned' ); 110 | assert.equal( calls, 1, 'Result was not cached' ); 111 | assert.equal( first, second, 'Cached result is incorrect' ); 112 | }); 113 | 114 | it( 'should cache falsy values', () => { 115 | let calls = 0; 116 | let result; 117 | 118 | function fn() { 119 | calls++; 120 | return ( result = null ); 121 | } 122 | 123 | let mem = memoize( fn ); 124 | 125 | let first = mem( 123 ); 126 | let second = mem( 123 ); 127 | 128 | assert.equal( first, result, 'Incorrect result was returned' ); 129 | assert.equal( calls, 1, 'Result was not cached' ); 130 | assert.equal( first, second, 'Cached result is incorrect' ); 131 | }); 132 | 133 | it( 'should expire an element after a ttl' , done => { 134 | let fn = function() { 135 | return Math.random(); 136 | } 137 | let mem = memoize( fn, { ttl: 10 } ); 138 | 139 | let first = mem(); 140 | let second = mem(); 141 | assert.equal( first, second ); 142 | 143 | setTimeout( function() { 144 | let newFirst = mem(); 145 | 146 | assert.notEqual( first, newFirst ); 147 | done(); 148 | }, 11 ); 149 | }); 150 | 151 | it( 'should work with promises', done => { 152 | let calls = 0; 153 | let result; 154 | 155 | function fn() { 156 | calls++; 157 | return Promise.resolve( result = {} ); 158 | } 159 | 160 | let mem = memoize( fn, { async: true } ); 161 | 162 | let first; 163 | let second; 164 | 165 | mem('foo').then( res => first = result ) 166 | .then( () => mem('foo').then( res => second = result ) ) 167 | .then( () => { 168 | assert.equal( first, result, 'Incorrect result was returned' ); 169 | assert.equal( calls, 1, 'Result was not cached' ); 170 | assert.equal( first, second, 'Cached result is incorrect' ); 171 | done(); 172 | }) 173 | .catch( done ); 174 | }); 175 | }); 176 | --------------------------------------------------------------------------------