Last active
November 29, 2018 23:30
-
-
Save drenther/f2a1f97331fec6f81f3ca32a0206982c to your computer and use it in GitHub Desktop.
Structural Pattern - Proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Target | |
function networkFetch(url) { | |
return `${url} - Response from network`; | |
} | |
// Proxy | |
// ES6 Proxy API = new Proxy(target, handler); | |
const cache = []; | |
const proxiedNetworkFetch = new Proxy(networkFetch, { | |
apply(target, thisArg, args) { | |
const urlParam = args[0]; | |
if (cache.includes(urlParam)) { | |
return `${urlParam} - Response from cache`; | |
} else { | |
cache.push(urlParam); | |
return Reflect.apply(target, thisArg, args); | |
} | |
}, | |
}); | |
// usage | |
console.log(proxiedNetworkFetch('dogPic.jpg')); // 'dogPic.jpg - Response from network' | |
console.log(proxiedNetworkFetch('dogPic.jpg')); // 'dogPic.jpg - Response from cache' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment