Skip to content

Instantly share code, notes, and snippets.

@PetukhovArt
Created December 29, 2024 16:11
Show Gist options
  • Save PetukhovArt/7b6a563962bc2746fac6290b2a00e62f to your computer and use it in GitHub Desktop.
Save PetukhovArt/7b6a563962bc2746fac6290b2a00e62f to your computer and use it in GitHub Desktop.
js-grill
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