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

Commit

Permalink
Remove browser-specific memoization
Browse files Browse the repository at this point in the history
  • Loading branch information
rtsao committed Sep 19, 2018
1 parent 4b0b7b8 commit 612a16d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 25 deletions.
10 changes: 10 additions & 0 deletions src/__tests__/memoize.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,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();
});
29 changes: 4 additions & 25 deletions src/memoize.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,34 +11,13 @@ import type {Context} from './types.js';
type MemoizeFn<A> = (ctx: Context) => A;

export function memoize<A>(fn: MemoizeFn<A>): MemoizeFn<A> {
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;
return ((wm.get(ctx): any): A); // Refinement with `has` doesn't seem to work
}
return memoized;
const result = fn(ctx);
wm.set(ctx, result);
return result;
};
}

0 comments on commit 612a16d

Please sign in to comment.