Pascal's Triangle
Last updated
Last updated
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
// 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);
};
}
codesandbox - Pascal Triangle
replit - decorating methods