From 48515c76c3ae573d754da121a07dd274730447e6 Mon Sep 17 00:00:00 2001 From: Doug Gale Date: Mon, 19 Oct 2015 02:17:29 -0400 Subject: [PATCH] Make forEach have the same interface as Array.prototype.forEach --- lib/simple_lru.js | 9 ++++----- test/simple_lru_tests.js | 38 +++++++++++++++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/lib/simple_lru.js b/lib/simple_lru.js index 26f92fd..6d07631 100644 --- a/lib/simple_lru.js +++ b/lib/simple_lru.js @@ -136,11 +136,10 @@ Cache.prototype.detach = function(element){ this.size-- } -Cache.prototype.forEach = function(callback){ - var self = this +Cache.prototype.forEach = function(callback, thisArg){ Object.keys(this.cache).forEach(function(key){ - var val = self.cache[key] - callback(val.value,key) - }) + var val = this.cache[key] + callback.call(thisArg, val.value, key, this) + }, this) } module.exports=Cache diff --git a/test/simple_lru_tests.js b/test/simple_lru_tests.js index 1229e05..f45bb8d 100644 --- a/test/simple_lru_tests.js +++ b/test/simple_lru_tests.js @@ -58,5 +58,41 @@ describe("BigCache Config",function(){ for(var i = 0; i < 100; i++) cache.get(i).should.equal("value_"+i+"_modif") - }) + }) + it("Should have forEach with the same interface as Array#forEach", function() { + var cache = new SimpleCache({maxSize:10}) + for(var i = 1; i <= 10; i++) + cache.set(i,"value_"+i) + + var testContext1 = { test:1 } + var testContext2 = { other: 2 } + + cache.forEach(function(value,key,passedCache){ + should.exist(this) + should.exist(this.test) + should.exist(value) + should.exist(key) + should.exist(passedCache) + should(key).be.a.String(); + should(passedCache).be.instanceof(SimpleCache); + this.should.equal(testContext1) + this.test.should.equal(1) + value.should.equal("value_" + key) + should(+key).be.greaterThanOrEqual(1) + should(+key).be.lessThanOrEqual(10) + passedCache.should.equal(cache) + }, testContext1); + + cache.forEach(function(value,key,passedCache){ + should.exist(this) + should.exist(this.other) + this.other.should.be.equal(2) + this.should.equal(testContext2) + }, testContext2); + + var returnValue = cache.forEach(function(value, key) { + return 42; + }); + should(returnValue).be.undefined(); + }) })