Skip to content

Commit

Permalink
Add peek()
Browse files Browse the repository at this point in the history
  • Loading branch information
voxpelli committed Oct 26, 2017
1 parent cb59fbe commit fcc8495
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 0 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ There are a few basic things that all caches support.
If `recordStats` is set to `false`, then the get won't increase any metrics
or affect any stats of a bounded cache.

* `cache.peek(key): mixed|null`

Same as `getIfPresent(key, false)`. Will return the cached value, but never
load a value if it does not exist and not affect any metrics or stats of
the cache.

* `cache.has(key): boolean`

Check if the given key exists in the cache. The key can be either a
Expand Down
4 changes: 4 additions & 0 deletions cache/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ module.exports = class BaseCache {
throwError();
}

peek(key) {
return this.getIfPresent(key, false);
}

delete(key) {
throwError();
}
Expand Down
5 changes: 5 additions & 0 deletions test/base.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ describe('BaseCache', function() {
expect(() => cache.getIfPresent('key')).to.throw();
});

it('peek throws', function() {
const cache = new BaseCache();
expect(() => cache.peek('key')).to.throw();
});

it('delete throws', function() {
const cache = new BaseCache();
expect(() => cache.delete('key')).to.throw();
Expand Down
1 change: 1 addition & 0 deletions test/bounded.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ describe('BoundedCache', function() {

expect(cache.has('key')).to.equal(true);
expect(cache.get('key')).to.equal('value');
expect(cache.peek('key')).to.equal('value');
});

it('Get non-existent value in cache', function() {
Expand Down
10 changes: 10 additions & 0 deletions test/metrics.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,14 @@ describe('MetricsCache', function() {
expect(cache.metrics.misses).to.equal(0);
expect(cache.metrics.hitRate).to.equal(1);
});

it('Peek without recording stats', function() {
const cache = newCache();

expect(cache.peek('key')).to.equal(null);

expect(cache.metrics.hits).to.equal(0);
expect(cache.metrics.misses).to.equal(0);
expect(cache.metrics.hitRate).to.equal(1);
});
});

0 comments on commit fcc8495

Please sign in to comment.