forked from knaxus/problem-solving-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRUCache.test.js
73 lines (61 loc) · 2.74 KB
/
LRUCache.test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const { LRUCache } = require('.');
describe('Algorithms: LRU Cache', () => {
describe('LRUCache Instance', () => {
it('Should be a class', () => {
expect(typeof LRUCache.prototype.constructor).toEqual('function');
});
});
describe('LRUCache API', () => {
let lruCache = new LRUCache(4);
beforeEach(() => {
lruCache = new LRUCache(4);
});
describe('get(key)', () => {
it('Should return false if the LRUCache is empty', () => {
expect(lruCache.get('foo')).toEqual(false);
});
it('Should return cached value if the key exists in the LRUCache', () =>{
lruCache.set('foo', 'bar');
expect(lruCache.get('foo')).toEqual('bar');
});
it('Should move least recently used key to the beginning of the list', () => {
lruCache.set('key1', 'value1');
lruCache.set('key2', 'value2');
expect(lruCache.list.head.next.data['key']).toEqual('key2');
expect(lruCache.list.head.next.data['value']).toEqual('value2');
// The least recently used key is moved at the beginning of the list
lruCache.get('key1');
expect(lruCache.list.head.next.data['key']).toEqual('key1');
expect(lruCache.list.head.next.data['value']).toEqual('value1');
});
});
describe('set(key, value)', () =>{
it('Should append each <key:value> pair to the beginning of list', () => {
lruCache.set('foo', 'bar');
expect(lruCache.list.head.next.data['key']).toEqual('foo');
expect(lruCache.list.head.next.data['value']).toEqual('bar');
});
it('Should update value if key already exists', () => {
lruCache.set('foo', 'bar');
lruCache.set('foo', 'newBar');
expect(lruCache.get('foo')).toEqual('newBar');
});
it('Should remove node at the end if the LRUCache capacity is filled', () => {
lruCache.set('key5', 'value5');
lruCache.set('key4', 'value4');
lruCache.set('key3', 'value3');
lruCache.set('key2', 'value2');
lruCache.set('key1', 'value1');
expect(lruCache.list.length()).toEqual(lruCache.size);
expect(lruCache.list.head.next.data['key']).toEqual('key1');
expect(lruCache.list.head.next.data['value']).toEqual('value1');
expect(lruCache.list.head.next.next.data['key']).toEqual('key2');
expect(lruCache.list.head.next.next.data['value']).toEqual('value2');
expect(lruCache.list.head.next.next.next.data['key']).toEqual('key3');
expect(lruCache.list.head.next.next.next.data['value']).toEqual('value3');
expect(lruCache.list.head.next.next.next.next.data['key']).toEqual('key4');
expect(lruCache.list.head.next.next.next.next.data['value']).toEqual('value4');
});
});
});
});