From 43c13c22a8d9faff4284b74a8ba1fdacb4aeee05 Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Wed, 7 May 2014 00:40:27 -0700 Subject: [PATCH] Make `_.memoize` skip the `__proto__` key. --- lodash.js | 8 +++++--- test/test.js | 36 +++++++++++++++++++++++------------- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/lodash.js b/lodash.js index e9e7dea6c..572f7cab4 100644 --- a/lodash.js +++ b/lodash.js @@ -5340,9 +5340,11 @@ throw new TypeError(funcErrorText); } var memoized = function() { - var cache = memoized.cache, - key = resolver ? resolver.apply(this, arguments) : '_' + arguments[0]; - + var key = resolver ? resolver.apply(this, arguments) : arguments[0]; + if (key == '__proto__') { + return func.apply(this, arguments); + } + var cache = memoized.cache; return hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = func.apply(this, arguments)); diff --git a/test/test.js b/test/test.js index 1a6ff086d..dd48716db 100644 --- a/test/test.js +++ b/test/test.js @@ -3443,15 +3443,6 @@ deepEqual(_.uniq(largeArray), expected); deepEqual(_.without.apply(_, [largeArray].concat(largeArray)), []); }); - - test('lodash.memoize should support values that resolve to the `__proto__` key', 1, function() { - var count = 0, - memoized = _.memoize(function() { return ++count; }); - - memoized('__proto__'); - memoized('__proto__'); - strictEqual(count, 1); - }); }()); /*--------------------------------------------------------------------------*/ @@ -6098,16 +6089,35 @@ }); test('should expose a `cache` object on the `memoized` function', 4, function() { - _.each(['_a', 'a'], function(key, index) { - var memoized = _.memoize(_.identity, index && _.identity); + _.times(2, function(index) { + var resolver = index && _.identity, + memoized = _.memoize(_.identity, resolver); memoized('a'); - strictEqual(memoized.cache[key], 'a'); + strictEqual(memoized.cache.a, 'a'); - memoized.cache[key] = 'b'; + memoized.cache.a = 'b'; strictEqual(memoized('a'), 'b'); }); }); + + test('should skip the `__proto__` key', 4, function() { + _.times(2, function(index) { + var count = 0, + resolver = index && _.identity; + + var memoized = _.memoize(function() { + count++; + return []; + }, resolver); + + memoized('__proto__'); + memoized('__proto__'); + + strictEqual(count, 2); + ok(!(memoized.cache instanceof Array)); + }); + }); }()); /*--------------------------------------------------------------------------*/