Browse files

[minor] Added Expirable#forEach

[dist] 0.0.5
  • Loading branch information...
1 parent 751e4b0 commit 19ce98b13cd2f331e3ab9b748ec9d20874b09667 @3rd-Eden committed Feb 20, 2013
Showing with 47 additions and 1 deletion.
  1. +9 −0 README.md
  2. +24 −0 index.js
  3. +1 −1 package.json
  4. +13 −0 tests/expirable.test.js
View
9 README.md
@@ -59,4 +59,13 @@ var stream = cache.stream('key', fs.createReadStream(..), '10 seconds');
// stream is the result of fs.createReadStream
// once the stream fires it's `done` event, we will store the data.
+
+// iterate over the cache
+cache.forEach(function (key, value) {
+ console.log(key, value);
+});
```
+
+## License
+
+MIT
View
24 index.js
@@ -193,6 +193,30 @@ Expire.prototype.remove = function remove(key, expired) {
};
/**
+ * Iterate over all the keys in our cache.
+ *
+ * @param {Function} iterator
+ * @param {String} context
+ * @api public
+ */
+Expire.prototype.forEach = function forEach(iterator, context) {
+ var now = Date.now();
+
+ Object.keys(this.cache).forEach(function iterating(key) {
+ var data = this.cache[key];
+
+ // Make sure that it's not expired.
+ if (now - data.last >= data.expires) {
+ return this.remove(key, true);
+ }
+
+ iterator.call(context || this, key, data.value, data.expires);
+ }, this);
+
+ return this;
+};
+
+/**
* Scans the cache for potential items that should expire.
*
* @api private
View
2 package.json
@@ -1,6 +1,6 @@
{
"name": "expirable",
- "version": "0.0.4",
+ "version": "0.0.5",
"description": "Expirable cache",
"main": "index.js",
"scripts": {
View
13 tests/expirable.test.js
@@ -150,4 +150,17 @@ describe('Expirable', function () {
done();
});
});
+
+ it('should be able to iterate over the cache', function () {
+ var cache = new Expirable('10 hours');
+
+ cache.set('foo', 'bar');
+ cache.forEach(function (key, value) {
+ expect(this).to.equal(cache);
+ expect(key).to.equal('foo');
+ expect(value).to.equal('bar');
+ });
+
+ cache.destroy();
+ });
});

0 comments on commit 19ce98b

Please sign in to comment.