Skip to content
This repository has been archived by the owner on Aug 10, 2023. It is now read-only.

Commit

Permalink
Create a fallback for systems where WeakMap is not available (#3)
Browse files Browse the repository at this point in the history
Create a fallback for systems where WeakMap is not available - When no weakmap exists, don't memoise
  • Loading branch information
omrilotan authored Jul 16, 2018
1 parent 95ab153 commit 40cc223
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 11 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "page-timing",
"version": "1.0.1",
"version": "1.0.2",
"description": "Measure browser timing and do something with it",
"author": "Fiverr SRE",
"license": "MIT",
Expand Down
10 changes: 7 additions & 3 deletions src/memoise/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
const mem = new WeakMap();

/**
* Memoises value by reference
* @param {Object} key
* @param {Function} fn
* @return {Any}
*/
export const memoise = (key, fn) => mem.has(key) ? mem.get(key) : mem.set(key, fn()).get(key);
export const memoise = (() => {
if (typeof WeakMap !== 'function') {
return (key, fn) => fn();
}
const mem = new WeakMap();
return (key, fn) => mem.has(key) ? mem.get(key) : mem.set(key, fn()).get(key);
})();
24 changes: 17 additions & 7 deletions src/memoise/spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
describe('memoise', () => {
const weakMap = global.WeakMap;
let memoise;
const key = {};

Expand All @@ -7,19 +8,18 @@ describe('memoise', () => {
memoise = require('.').memoise;
});

it('Should uses the getter to retrieve the value', () => {
memoise(key, () => 'Thang');
expect(memoise(key)).to.equal('Thang');
after(() => {
global.WeakMap = weakMap;
});

it('Should return the value', () =>
expect(memoise(key, () => 'Thang')).to.equal('Thang')
it('Should uses the getter to retrieve the value', () =>
expect(memoise({}, () => 'Thang')).to.equal('Thang')
);

it('Should memoise the result', () => {
memoise(key, () => 'Thing');
memoise(key, () => 'Thang');
expect(memoise(key)).to.equal('Thing');
expect(memoise(key, () => 'Thang')).to.equal('Thing');
expect(memoise(key, () => 'Thong')).to.equal('Thing');
});

it('Should throw error when trying to memoise primitives', () =>
Expand All @@ -29,4 +29,14 @@ describe('memoise', () => {
4,
].forEach((key) => expect(() => memoise(key, () => 'Thing')).to.throw())
);

it('Should fall back to using an object when weakmap is not available', () => {
global.WeakMap = null;
delete require.cache[require.resolve('.')];
memoise = require('.').memoise;

expect(() => memoise(key, () => 'Thang')).not.to.throw();
expect(memoise(key, () => 'Thang')).to.equal('Thang');
expect(memoise(key, () => 'Thong')).not.to.equal('Thang');
});
});

0 comments on commit 40cc223

Please sign in to comment.