Skip to content

Commit

Permalink
Polyfill correct Map#set and Set#add return behavior.
Browse files Browse the repository at this point in the history
Implementing my own suggestion:
#4012 (review)

This change would be sufficient to fix #4024, though #4012 helps as well.
  • Loading branch information
benjamn committed Oct 24, 2018
1 parent 39778af commit 3e2a00f
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions packages/apollo-cache-inmemory/src/fixPolyfills.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,23 @@
const frozen = {};
const frozenTestMap = new Map();
// Make sure Map.prototype.set returns the Map instance, per spec.
// https://github.com/apollographql/apollo-client/issues/4024
const testMap = new Map();
if (testMap.set(1, 2) !== testMap) {
const { set } = testMap;
Map.prototype.set = function (...args) {
return set.apply(this, args) || this;
};
}

// Make sure Set.prototype.add returns the Set instance, per spec.
const testSet = new Set();
if (testSet.add(3) !== testSet) {
const { add } = testSet;
Set.prototype.add = function (...args) {
return add.apply(this, args) || this;
};
}

const frozen = {};
if (typeof Object.freeze === 'function') {
Object.freeze(frozen);
}
Expand All @@ -12,13 +29,13 @@ try {
// objects before they become non-extensible:
// https://github.com/facebook/react-native/blob/98a6f19d7c/Libraries/vendor/core/Map.js#L44-L50
// https://github.com/apollographql/react-apollo/issues/2442#issuecomment-426489517
frozenTestMap.set(frozen, frozen).delete(frozen);
testMap.set(frozen, frozen).delete(frozen);
} catch {
const wrap = (method: <T>(obj: T) => T): typeof method => {
return method && (obj => {
try {
// If .set succeeds, also call .delete to avoid leaking memory.
frozenTestMap.set(obj, obj).delete(obj);
testMap.set(obj, obj).delete(obj);
} finally {
// If .set or .delete fails, the exception will be silently swallowed
// by this return-from-finally statement:
Expand Down

0 comments on commit 3e2a00f

Please sign in to comment.