Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Created October 26, 2025 14:14
Show Gist options
  • Select an option

  • Save mustafadalga/3434e310ffed947b87087ff689487d9f to your computer and use it in GitHub Desktop.

Select an option

Save mustafadalga/3434e310ffed947b87087ff689487d9f to your computer and use it in GitHub Desktop.
Demonstrates how to use JavaScript’s Proxy API to intercept function calls via the apply trap and implement simple caching (memoization) logic.
const map = new Map()
const target = async (property: string) => {
const random = (Math.random() * (2000 - 100)) + 100
await new Promise(resolve => setTimeout(resolve, random))
console.log(`fetch ${property} detail`)
return Date.now()
}
const handler = {
apply: async (target: (property: string) => Promise<number>, thisArg: unknown, argumentList: [ string ]): Promise<number> => {
const property = argumentList[0]
if (map.has(property)) {
return map.get(property)
}
const data = await target.apply(thisArg, argumentList)
map.set(property, data)
return data
},
}
async function test() {
const proxy = new Proxy(target, handler)
console.log(await proxy("1"))
console.log(await proxy("1"))
console.log(await proxy("1"))
console.log(await proxy("2"))
}
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment