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

Use a WeakMap to store memoized values #298

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions src/__tests__/memoize.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@ import {memoize} from '../memoize';
import type {Context} from '../types.js';

test('memoize', t => {
// $FlowFixMe
const mockCtx: Context = {
memoized: new Map(),
};
const mockCtx: Context = ({}: any);

let counter = 0;
const memoized = memoize(() => {
Expand All @@ -33,5 +30,15 @@ test('memoize', t => {
t.equal(memoizedB(mockCtx), 1, 'memoizes correctly');
t.equal(memoized(mockCtx), 1, 'calls function when it has no value');
t.equal(memoized(mockCtx), 1, 'memoizes correctly');

// New context object should cause new calculation
const mockCtx2: Context = ({}: any);
t.equal(memoized(mockCtx2), 2, 'calls function when it has no value');
t.equal(memoized(mockCtx2), 2, 'memoizes correctly');
t.equal(memoizedB(mockCtx2), 2, 'calls function when it has no value');
t.equal(memoizedB(mockCtx2), 2, 'memoizes correctly');
t.equal(memoized(mockCtx2), 2, 'calls function when it has no value');
t.equal(memoized(mockCtx2), 2, 'memoizes correctly');

t.end();
});
12 changes: 5 additions & 7 deletions src/memoize.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,14 @@ 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);
const wm = new WeakMap();
return ctx => {
if (wm.has(ctx)) {
return ((wm.get(ctx): any): A); // Refinement with `has` doesn't seem to work
}
const result = fn(ctx);
ctx.memoized.set(memoizeKey, result);
wm.set(ctx, result);
return result;
};
}
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