Skip to content

Commit c0dc5ea

Browse files
committed
Use a Map in _.memoize
Closes jashkenas#1862.
1 parent 49f594b commit c0dc5ea

File tree

2 files changed

+8
-8
lines changed

2 files changed

+8
-8
lines changed

test/functions.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -132,10 +132,10 @@
132132
});
133133
equal(upper('foo'), 'FOO');
134134
equal(upper('bar'), 'BAR');
135-
deepEqual(upper.cache, {foo: 'FOO', bar: 'BAR'});
136-
upper.cache = {foo: 'BAR', bar: 'FOO'};
135+
equal(upper.cache.get('foo'), 'FOO');
136+
equal(upper.cache.get('bar'), 'BAR');
137+
upper.cache.set('foo', 'BAR');
137138
equal(upper('foo'), 'BAR');
138-
equal(upper('bar'), 'FOO');
139139

140140
var hashed = _.memoize(function(key) {
141141
//https://github.com/jashkenas/underscore/pull/1679#discussion_r13736209
@@ -145,7 +145,7 @@
145145
return key.toUpperCase();
146146
});
147147
hashed('yep');
148-
deepEqual(hashed.cache, {'YEP': 'yep'}, 'takes a hasher');
148+
equal(hashed.cache.get('YEP'), 'yep', 'takes a hasher');
149149

150150
// Test that the hash function can be used to swizzle the key.
151151
var objCacher = _.memoize(function(value, key) {

underscore.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -789,11 +789,11 @@
789789
_.memoize = function(func, hasher) {
790790
var memoize = function(key) {
791791
var cache = memoize.cache;
792-
var address = '' + (hasher ? hasher.apply(this, arguments) : key);
793-
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
794-
return cache[address];
792+
var address = hasher ? hasher.apply(this, arguments) : key;
793+
if (!cache.has(address)) cache.set(address, func.apply(this, arguments));
794+
return cache.get(address);
795795
};
796-
memoize.cache = {};
796+
memoize.cache = new Map();
797797
return memoize;
798798
};
799799

0 commit comments

Comments
 (0)