function memoizedFunction(func) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) {
return cache[key];
}
const result = func.apply(this, args);
cache[key] = result;
return result;
};
}
function expensiveCalculation(n) {
// 비용이 많이 드는 계산을 수행하는 함수
console.log('Calculating...');
return n * 2;
}
const memoizedCalculation = memoizedFunction(expensiveCalculation);
console.log(memoizedCalculation(5)); // 처음 호출되므로 계산 수행 후 결과 반환
console.log(memoizedCalculation(5)); // 이전에 계산된 결과를 반환하여 중복 계산 피함