mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
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:
@ -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
|
||||
})
|
||||
})
|
||||
})
|
||||
|
Reference in New Issue
Block a user