forked from andyburke/antisync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemoize.js
38 lines (36 loc) · 1.08 KB
/
memoize.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
'use strict';
var timing = require( './timing' );
module.exports = function memoize( fn, hasher ) {
var memo = {};
var queues = {};
hasher = hasher || function( x ) {
return x;
};
var memoized = function() {
var args = Array.prototype.slice.call( arguments );
var callback = args.pop();
var key = hasher.apply( null, args );
if ( key in memo ) {
timing.nextTick( function() {
callback.apply( null, memo[ key ] );
} );
}
else if ( key in queues ) {
queues[ key ].push( callback );
}
else {
queues[ key ] = [ callback ];
fn.apply( null, args.concat( [ function() {
memo[ key ] = arguments;
var q = queues[ key ];
delete queues[ key ];
for ( var i = 0, l = q.length; i < l; i++ ) {
q[ i ].apply( null, arguments );
}
} ] ) );
}
};
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
};