Created
October 26, 2025 14:14
-
-
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.
This file contains hidden or 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
| 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