Skip to content
This repository has been archived by the owner on May 17, 2019. It is now read-only.

Commit

Permalink
Use WeakMap to memoize rather than mutating ctx
Browse files Browse the repository at this point in the history
  • Loading branch information
rtsao committed Sep 19, 2018
1 parent 10934e4 commit fca2d93
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 10 deletions.
37 changes: 28 additions & 9 deletions src/memoize.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,35 @@ import type {Context} from './types.js';

type MemoizeFn<A> = (ctx: Context) => A;

function Container() {}

export function memoize<A>(fn: MemoizeFn<A>): MemoizeFn<A> {
const memoizeKey = __NODE__ ? Symbol('memoize-key') : new Container();
return function memoized(ctx: Context) {
if (ctx.memoized.has(memoizeKey)) {
return ctx.memoized.get(memoizeKey);
if (__BROWSER__) {
return browserMemoize(fn);
}

const wm = new WeakMap();
return ctx => {
if (wm.has(ctx)) {
return ((wm.get(ctx): any): A); // Refinement doesn't seem to work
} else {
const result = fn(ctx);
wm.set(ctx, result);
return result;
}
};
}

/**
* There is only ever a single ctx object in the browser.
* Therefore we can use a simple memoization function.
*/
function browserMemoize<A>(fn: MemoizeFn<A>): MemoizeFn<A> {
let memoized;
let called = false;
return ctx => {
if (!called) {
memoized = fn(ctx);
called = true;
}
const result = fn(ctx);
ctx.memoized.set(memoizeKey, result);
return result;
return memoized;
};
}
1 change: 0 additions & 1 deletion src/plugins/timing.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ const timing: TimingPlugin = {
export const TimingToken: Token<TimingPlugin> = createToken('TimingToken');

function middleware(ctx, next) {
ctx.memoized = new Map();
const {start, render, end, downstream, upstream} = timing.from(ctx);
ctx.timing = {
start,
Expand Down

0 comments on commit fca2d93

Please sign in to comment.