Created
December 11, 2019 18:22
-
-
Save feliperohdee/cc9976f5bccb9254fb8c53889fd8f1ae to your computer and use it in GitHub Desktop.
LRU cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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