|
| 1 | +import { LRUCache } from './lru-cache'; |
| 2 | + |
| 3 | +describe('LRUCache', () => { |
| 4 | + let cache: LRUCache; |
| 5 | + |
| 6 | + beforeEach(() => { |
| 7 | + cache = new LRUCache(2); |
| 8 | + }); |
| 9 | + |
| 10 | + it('should insert and retrieve a value', () => { |
| 11 | + cache.set('a', 'apple'); |
| 12 | + expect(cache.get('a')).toBe('apple'); |
| 13 | + }); |
| 14 | + |
| 15 | + it('should return undefined for missing values', () => { |
| 16 | + expect(cache.get('missing')).toBeUndefined(); |
| 17 | + }); |
| 18 | + |
| 19 | + it('should overwrite existing values', () => { |
| 20 | + cache.set('a', 'apple'); |
| 21 | + cache.set('a', 'avocado'); |
| 22 | + expect(cache.get('a')).toBe('avocado'); |
| 23 | + }); |
| 24 | + |
| 25 | + it('should evict least recently used item', () => { |
| 26 | + cache.set('a', 'apple'); |
| 27 | + cache.set('b', 'banana'); |
| 28 | + cache.set('c', 'cherry'); |
| 29 | + expect(cache.get('a')).toBeUndefined(); |
| 30 | + expect(cache.get('b')).toBe('banana'); |
| 31 | + expect(cache.get('c')).toBe('cherry'); |
| 32 | + }); |
| 33 | + |
| 34 | + it('should move recently used item to the end of the cache', () => { |
| 35 | + cache.set('a', 'apple'); |
| 36 | + cache.set('b', 'banana'); |
| 37 | + cache.get('a'); // Access 'a' to make it recently used |
| 38 | + cache.set('c', 'cherry'); |
| 39 | + expect(cache.get('a')).toBe('apple'); |
| 40 | + expect(cache.get('b')).toBeUndefined(); |
| 41 | + expect(cache.get('c')).toBe('cherry'); |
| 42 | + }); |
| 43 | + |
| 44 | + it('should check if a key exists', () => { |
| 45 | + cache.set('a', 'apple'); |
| 46 | + expect(cache.has('a')).toBeTruthy(); |
| 47 | + expect(cache.has('b')).toBeFalsy(); |
| 48 | + }); |
| 49 | + |
| 50 | + it('should handle the cache capacity of zero', () => { |
| 51 | + const zeroCache = new LRUCache(0); |
| 52 | + zeroCache.set('a', 'apple'); |
| 53 | + expect(zeroCache.get('a')).toBeUndefined(); |
| 54 | + }); |
| 55 | + |
| 56 | + it('should handle the cache capacity of one', () => { |
| 57 | + const oneCache = new LRUCache(1); |
| 58 | + oneCache.set('a', 'apple'); |
| 59 | + expect(oneCache.get('a')).toBe('apple'); |
| 60 | + oneCache.set('b', 'banana'); |
| 61 | + expect(oneCache.get('a')).toBeUndefined(); |
| 62 | + expect(oneCache.get('b')).toBe('banana'); |
| 63 | + }); |
| 64 | +}); |
0 commit comments