Permalink
Browse files

keys() and values()

  • Loading branch information...
1 parent 566f444 commit 8630dbd6e4c6894c3c5cd5f918ebcc4cbd78f2fd @isaacs committed Nov 29, 2012
Showing with 47 additions and 0 deletions.
  1. +8 −0 README.md
  2. +20 −0 lib/lru-cache.js
  3. +19 −0 test/foreach.js
View
@@ -77,3 +77,11 @@ away.
Just like `Array.prototype.forEach`. Iterates over all the keys
in the cache, in order of recent-ness. (Ie, more recently used
items are iterated over first.)
+
+* `keys()`
+
+ Return an array of the keys in the cache.
+
+* `values()`
+
+ Return an array of the values in the cache.
View
@@ -108,6 +108,26 @@ function LRUCache (options) {
}
}
+ this.keys = function () {
+ var keys = new Array(itemCount)
+ var i = 0
+ for (var k = mru - 1; k >= 0; k--) if (lruList[k]) {
+ var hit = lruList[k]
+ keys[i++] = hit.key
+ }
+ return keys
+ }
+
+ this.values = function () {
+ var values = new Array(itemCount)
+ var i = 0
+ for (var k = mru - 1; k >= 0; k--) if (lruList[k]) {
+ var hit = lruList[k]
+ values[i++] = hit.value
+ }
+ return values
+ }
+
this.reset = function () {
if (dispose) {
for (var k in cache) {
View
@@ -31,3 +31,22 @@ test('forEach', function (t) {
t.end()
})
+
+test('keys() and values()', function (t) {
+ var l = new LRU(5)
+ for (var i = 0; i < 10; i ++) {
+ l.set(i.toString(), i.toString(2))
+ }
+
+ t.similar(l.keys(), ['9', '8', '7', '6', '5'])
+ t.similar(l.values(), ['1001', '1000', '111', '110', '101'])
+
+ // get in order of most recently used
+ l.get(6)
+ l.get(8)
+
+ t.similar(l.keys(), ['8', '6', '9', '7', '5'])
+ t.similar(l.values(), ['1000', '110', '1001', '111', '101'])
+
+ t.end()
+})

0 comments on commit 8630dbd

Please sign in to comment.