-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustomCache.js
More file actions
27 lines (23 loc) · 1.03 KB
/
customCache.js
File metadata and controls
27 lines (23 loc) · 1.03 KB
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
/**
* Custom URL Cache using Closure and Higher Order Function concepts.
* The outer function `CustomURLCache` creates a private `cacheMap` object.
* The inner function returned has access to this `cacheMap` due to lexical scoping (closure).
* Each time the inner function is called with a URL, it checks if the URL is already cached.
* If it is, it returns the cached value; otherwise, it adds the URL to the cache.
*/
const CustomURLCache = function () {
const cacheMap = {};
return function(url = null) {
if(url && cacheMap[url]) {
console.log(`\nServing ${url} from Cache`);
return cacheMap[url];
}
console.log(`\nSetting ${url} into Cache`);
cacheMap[url] = true;
return false;
}
}
const urlCache = CustomURLCache();
console.log(urlCache("https://example.com/resource1")); // Setting into Cache - false
console.log(urlCache("https://google.com/search")); // Setting into Cache - false
console.log(urlCache("https://google.com/search")); // Serving from Cache - true