Skip to content

Instantly share code, notes, and snippets.

@feliperohdee
Created December 11, 2019 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feliperohdee/cc9976f5bccb9254fb8c53889fd8f1ae to your computer and use it in GitHub Desktop.
Save feliperohdee/cc9976f5bccb9254fb8c53889fd8f1ae to your computer and use it in GitHub Desktop.
LRU cache
const _ = require('lodash');
const LRU = require('lru-cache');
class Cache {
constructor(maxSizeInMB = 128) {
this.lru = new LRU({
max: maxSizeInMB * 1e+6,
length: n => Buffer.byteLength(n, 'utf8')
});
}
max(MB) {
this.lru.max = MB * 1e+6;
}
get(key) {
return this.lru.get(key) || null;
}
set(key, value) {
if (!_.isString(key) || !_.isString(value)) {
throw new Error('key and value must be strings.');
}
return this.lru.set(key, value);
}
}
module.exports = new Cache();
const chai = require('chai');
const cache = require('./cache');
const expect = chai.expect;
describe('libs/cache.js', () => {
describe('max', () => {
it('should change max', () => {
expect(cache.lru.max).to.equal(128 * 1e+6);
cache.max(0.000001);
expect(cache.lru.max).to.equal(0.000001 * 1e+6);
});
});
describe('get', () => {
before(() => {
cache.set('a', 'b');
});
it('should get', () => {
expect(cache.get('a')).to.equal('b');
});
it('should get null', () => {
expect(cache.get('b')).to.be.null;
});
});
describe('set', () => {
it('should not accept non stirng key', () => {
expect(() => cache.set(1, 'a')).to.throw('key and value must be strings.');
});
it('should not accept non stirng key', () => {
expect(() => cache.set('a', 1)).to.throw('key and value must be strings.');
});
it('should set and stale', () => {
cache.set('b', 'c');
expect(cache.get('a')).to.be.null;
expect(cache.get('b')).to.equal('c');
cache.set('c', 'd');
expect(cache.get('b')).to.be.null;
expect(cache.get('c')).to.equal('d');
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment