Skip to content

Instantly share code, notes, and snippets.

@nurpax
Last active June 4, 2019 20:45
Show Gist options
  • Save nurpax/b46329321cf0deff05c2137effc4b775 to your computer and use it in GitHub Desktop.
Save nurpax/b46329321cf0deff05c2137effc4b775 to your computer and use it in GitHub Desktop.
const _getExpensiveThing = () => {
const c: any = getExpensiveThing;
if (c.cache) {
return c.cache;
}
c.cache = expensiveThing();
return c.cache;
}
function memoize<T>(fn: () => T) {
let cache: T | undefined = undefined;
return () => {
if (cache === undefined) {
cache = fn();
}
return cache;
};
}
interface ExpensiveThing {
bar: number;
baz: number;
}
function expensiveThing(): ExpensiveThing {
console.log('computing expensive thing');
return { bar: 1, baz: 1 };
}
const getExpensiveThing = memoize(expensiveThing);
function tt() {
console.log(getExpensiveThing());
console.log(getExpensiveThing());
}
tt();
interface ExpensiveThing {
bar: number;
baz: number;
}
function expensiveThing(): ExpensiveThing {
return { bar: 1, baz: 1 };
}
const getExpensiveThing = () => {
const c: any = getExpensiveThing;
if (c.cache) {
return c.cache;
}
c.cache = expensiveThing();
return c.cache;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment