Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Created March 31, 2024 16:10
Show Gist options
  • Save mustafadalga/460ef1aa07eec5357e5e9887c0f5e26b to your computer and use it in GitHub Desktop.
Save mustafadalga/460ef1aa07eec5357e5e9887c0f5e26b to your computer and use it in GitHub Desktop.
Custom Memoization Function in JavaScript
/**
* This Gist demonstrates a simple yet effective implementation of a memoization function in JavaScript.
* Memoization is an optimization technique used to speed up computer programs by storing the results of expensive function
* calls and returning the cached result when the same inputs occur again.
*/
const memoMap = new Map();
const complexFunction = (a1: number[], a2: number[]): number => {
// Simulate heavy calculations
console.log("Performing heavy calculations...");
return a1.reduce((acc, val) => acc + val, 0) + a2.reduce((acc, val) => acc + val, 0); // Example calculation
};
const memo = (a1: number[], a2: number[]) => {
const key = JSON.stringify([ a1, a2 ]);
if (memoMap.has(key)) {
console.log("Returning cached result...");
return memoMap.get(key);
}
const result = complexFunction(a1, a2);
memoMap.set(key, result);
return result;
};
// Example usage
console.log(memo([ 1, 2, 3 ], [ 4, 5 ])); // Performs calculation
console.log(memo([ 1, 2, 3 ], [ 4, 5 ])); // Returns cached result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment