From ab3b9721853c2729103316c825d0ed71b8912d2e Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Fri, 28 Nov 2014 13:47:38 -0800 Subject: [PATCH] Add `mapDelete`. --- lodash.js | 14 ++++++++++++++ test/test.js | 36 ++++++++++++++++++++++++++++-------- 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/lodash.js b/lodash.js index a5080e2e4..b024f0f28 100644 --- a/lodash.js +++ b/lodash.js @@ -1445,6 +1445,19 @@ this.__data__ = {}; } + /** + * Removes `key` and its value from the cache. + * + * @private + * @name get + * @memberOf _.memoize.Cache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`. + */ + function mapDelete(key) { + return delete this.__data__[key]; + } + /** * Gets the cached value for `key`. * @@ -9970,6 +9983,7 @@ LodashWrapper.prototype = lodash.prototype; // Add functions to the `Map` cache. + MapCache.prototype['delete'] = mapDelete; MapCache.prototype.get = mapGet; MapCache.prototype.has = mapHas; MapCache.prototype.set = mapSet; diff --git a/test/test.js b/test/test.js index c10abba74..b66e42b20 100644 --- a/test/test.js +++ b/test/test.js @@ -7966,7 +7966,7 @@ memoized('a'); - deepEqual(_.functions(memoized.cache).sort(), ['get', 'has', 'set']); + deepEqual(_.functions(memoized.cache).sort(), ['delete', 'get', 'has', 'set']); }); }); @@ -7988,26 +7988,39 @@ }); }); - test('should allow `_.memoize.Cache` to be customized', 2, function() { - var oldCache = _.memoize.Cache; + test('should allow `_.memoize.Cache` to be customized', 4, function() { + var oldCache = _.memoize.Cache function Cache() { - this.__wrapped__ = []; + this.__data__ = []; } Cache.prototype = { + 'delete': function(key) { + var data = this.__data__; + + var index = _.findIndex(data, function(entry) { + return key === entry.key; + }); + + if (index < 0) { + return false; + } + data.splice(index, 1); + return true; + }, 'get': function(key) { - return _.find(this.__wrapped__, function(entry) { + return _.find(this.__data__, function(entry) { return key === entry.key; }).value; }, 'has': function(key) { - return _.some(this.__wrapped__, function(entry) { + return _.some(this.__data__, function(entry) { return key === entry.key; }); }, 'set': function(key, value) { - this.__wrapped__.push({ 'key': key, 'value': value }); + this.__data__.push({ 'key': key, 'value': value }); } }; @@ -8020,9 +8033,16 @@ var actual = memoized({ 'id': 'a' }); strictEqual(actual, '`id` is "a"'); - actual = memoized({ 'id': 'b' }); + var key = { 'id': 'b' }; + actual = memoized(key); strictEqual(actual, '`id` is "b"'); + var cache = memoized.cache; + strictEqual(cache.has(key), true); + + cache['delete'](key); + strictEqual(cache.has(key), false); + _.memoize.Cache = oldCache; }); }());