Pascal's Triangle
import { caching } from '../decorator/caching.js';
// binomial combinations
function _c(m, n) {
if (m - n < 0 || n < 0) return 0;
if (m - n === 0 || n === 0) return 1;
return _c(m - 1, n - 1) + _c(m - 1, n);
}
// give 'memory' to function '_c'
export const c = caching(_c);
caching decorator
// ⭐️ caching decorator
// use a closure to ecapsulate 'f'
export function caching(f) {
// make a new cache for this 'f'
let cache = new Map();
// returns a function that can remember
return function (...args) {
// if not in cache, cache it.
const key = `${args}`;
if (!cache.has(key)) {
// ╭- call a method -╮ ('f' could be a method)
let value = f.apply(this, args); // ⭐️ with "this" context
cache.set(key, value);
// log(`(${key}, ${value}) cached ...`);
}
// get function value from cache
return cache.get(key);
};
}
JS.info ⟩ Decorators and forwarding, call/apply
PJCHENder ⟩ [演算法] Fibonacci:善用 cache 和 Memoization 提升程式效能
codesandbox - Pascal Triangle
replit - decorating methods
Last updated