Skip to content

Instantly share code, notes, and snippets.

@drenther
Last active November 29, 2018 23:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drenther/f2a1f97331fec6f81f3ca32a0206982c to your computer and use it in GitHub Desktop.
Save drenther/f2a1f97331fec6f81f3ca32a0206982c to your computer and use it in GitHub Desktop.
Structural Pattern - Proxy
// 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