Created
December 29, 2024 16:11
-
-
Save PetukhovArt/7b6a563962bc2746fac6290b2a00e62f to your computer and use it in GitHub Desktop.
js-grill
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 plusFunction = (a: number, b: number) => a + b; | |
const memoFunction = (fn: (...args: any) => any) => { | |
const cache: Record<string, any> = {}; | |
return (...args: any) => { | |
const key = JSON.stringify(args); | |
if (cache[key]) { | |
return cache[key]; | |
} | |
const result = fn(...args); | |
cache[key] = result; | |
return result; | |
}; | |
}; | |
const memoPlus = memoFunction(plusFunction); | |
console.log(memoPlus(1, 2)); // 3 (вызов plus) | |
console.log(memoPlus(3, 1)); // 4 (вызов plus) | |
console.log(memoPlus(1, 2)); // 3 (обращение к cache) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment