· 6 years ago · Nov 03, 2019, 01:24 PM
1/*
2Implement a cache mechanism.
3
4It should be able to get, set and remove entries using the provided api below.
5In addition, we can provide the cache with the max amount of keys we want to store.
6
7If the cache is full when trying to set a key you should do the following:
8 1. Remove the most oudated key (the first key that entered the cache)
9 2. Save the new key with the value you received.
10
11See usage examples at the bottom of this file.
12*/
13
14class Cache {
15 constructor(maxKeys) {
16 // The cache will store up to maxKeys entries
17 this.maxKeys = maxKeys
18 this.keyArray = {}
19 this.keyArray.size = maxKeys
20 }
21
22 get(key) {
23 // retrieves value from cache by key
24 if (this.keyArray[key]) {
25 return this.keyArray[key]
26 } else {
27 return 'undefined'
28 }
29 }
30
31 getOr(key, fallback) {
32 // retrieves value from cache by key
33 // if value is undefined return the fallback
34 if (this.keyArray[key]){
35 return this.keyArray[key]
36 } else if (this.keyArray[key] === 'undefined'){
37 return fallback
38 }
39 }
40
41 set(key, value) {
42 // stores the value in the cache
43 // If the number of entries exceeds 'maxKeys' - remove the most outdated one
44 if (this.keyArray.keys >= this.maxKeys ){
45 this.clear(this.keyArray[Object.keys(this.keyArray).length-1])
46 this.keyArray[key] = value
47 } else {
48 this.keyArray[key] = value
49 }
50 }
51
52 clear(key) {
53 // removes the entry with this key
54 delete this.keyArray[key];
55 }
56}
57
58/*
59 This code should run and return the expected result
60 written as a comment at the end of each row.
61*/
62
63const cache = new Cache(100);
64
65cache.get('key'), // returns undefined
66cache.getOr('key', 10), // returns 10
67cache.set('key', 20), // returns 20
68cache.get('key'), // returns 20
69cache.clear('key'), // returns undefined
70cache.get('key') // returns undefined