merge: Improved LRUCache (#953)

* feat: added new validation test casses & methods

* style: formated with standard

* feat: added parse method & test cases

* docs: added js docs

* chore: added default import export
This commit is contained in:
Fahim Faisaal
2022-03-27 12:37:54 +06:00
committed by GitHub
parent 55da7a1d7c
commit 81c771b901
2 changed files with 171 additions and 28 deletions

View File

@ -1,9 +1,19 @@
import { LRUCache } from '../LRUCache'
import LRUCache from '../LRUCache'
import { fibonacciCache } from './cacheTest'
describe('LRUCache', () => {
it('Example 1 (Small Cache, size=2)', () => {
const cache = new LRUCache(2)
describe('Testing LRUCache', () => {
it('Testing with invalid capacity', () => {
expect(() => new LRUCache()).toThrow()
expect(() => new LRUCache('Invalid')).toThrow()
expect(() => new LRUCache(-1)).toThrow()
expect(() => new LRUCache(Infinity)).toThrow()
})
it('Example 1 (Small Cache, size = 2)', () => {
const cache = new LRUCache(1) // initially capacity
cache.capacity++ // now the capacity is increasing by one
cache.set(1, 1)
cache.set(2, 2)
@ -24,14 +34,41 @@ describe('LRUCache', () => {
expect(cache.get(3)).toBe(3)
expect(cache.get(4)).toBe(4)
expect(cache.cacheInfo()).toBe('CacheInfo(hits=6, misses=3, capacity=2, current size=2)')
expect(cache.info).toEqual({
misses: 3,
hits: 6,
capacity: 2,
size: 2
})
const json = '{"misses":3,"hits":6,"cache":{"3":3,"4":4}}'
expect(cache.toString()).toBe(json)
// merge with json
cache.parse(json)
cache.capacity-- // now the capacity decreasing by one
expect(cache.info).toEqual({
misses: 6,
hits: 12,
capacity: 1,
size: 1
})
})
it('Example 2 (Computing Fibonacci Series, size=100)', () => {
it('Example 2 (Computing Fibonacci Series, size = 100)', () => {
const cache = new LRUCache(100)
for (let i = 1; i <= 100; i++) {
fibonacciCache(i, cache)
}
expect(cache.cacheInfo()).toBe('CacheInfo(hits=193, misses=103, capacity=100, current size=98)')
expect(cache.info).toEqual({
misses: 103,
hits: 193,
capacity: 100,
size: 98
})
})
})