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

Commit fca2d93

Browse files
committed
Use WeakMap to memoize rather than mutating ctx
1 parent 10934e4 commit fca2d93

File tree

2 files changed

+28
-10
lines changed

2 files changed

+28
-10
lines changed

src/memoize.js

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,35 @@ import type {Context} from './types.js';
1010

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

13-
function Container() {}
14-
1513
export function memoize<A>(fn: MemoizeFn<A>): MemoizeFn<A> {
16-
const memoizeKey = __NODE__ ? Symbol('memoize-key') : new Container();
17-
return function memoized(ctx: Context) {
18-
if (ctx.memoized.has(memoizeKey)) {
19-
return ctx.memoized.get(memoizeKey);
14+
if (__BROWSER__) {
15+
return browserMemoize(fn);
16+
}
17+
18+
const wm = new WeakMap();
19+
return ctx => {
20+
if (wm.has(ctx)) {
21+
return ((wm.get(ctx): any): A); // Refinement doesn't seem to work
22+
} else {
23+
const result = fn(ctx);
24+
wm.set(ctx, result);
25+
return result;
26+
}
27+
};
28+
}
29+
30+
/**
31+
* There is only ever a single ctx object in the browser.
32+
* Therefore we can use a simple memoization function.
33+
*/
34+
function browserMemoize<A>(fn: MemoizeFn<A>): MemoizeFn<A> {
35+
let memoized;
36+
let called = false;
37+
return ctx => {
38+
if (!called) {
39+
memoized = fn(ctx);
40+
called = true;
2041
}
21-
const result = fn(ctx);
22-
ctx.memoized.set(memoizeKey, result);
23-
return result;
42+
return memoized;
2443
};
2544
}

src/plugins/timing.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,6 @@ const timing: TimingPlugin = {
4343
export const TimingToken: Token<TimingPlugin> = createToken('TimingToken');
4444

4545
function middleware(ctx, next) {
46-
ctx.memoized = new Map();
4746
const {start, render, end, downstream, upstream} = timing.from(ctx);
4847
ctx.timing = {
4948
start,

0 commit comments

Comments
 (0)