Skip to content

Commit

Permalink
[Fix] handle chrome/v8 bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
ljharb committed Sep 10, 2024
1 parent b2219f3 commit 266d8aa
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ var shimmedResult = set1.difference(set2);
assert.deepEqual(shimmedResult, new Set([1]));
```

## Compatibility
node v22 and equivalent versions of Chrome have Set difference, but has a bug with set-like arguments with non-SMI integer sizes.

## Tests
Simply clone the repo, `npm install`, and run `npm test`

Expand Down
21 changes: 20 additions & 1 deletion polyfill.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,24 @@ var Set = require('es-set/polyfill')();
var implementation = require('./implementation');

module.exports = function getPolyfill() {
return typeof Set.prototype.difference === 'function' ? Set.prototype.difference : implementation;
if (typeof Set.prototype.difference === 'function') {
var called = false;
var setLike = {
size: Infinity,
has: function () {},
keys: function () {
called = true;
return [].values();
}
};

new Set([1]).difference(setLike);
setLike.size = 2147483648; // 2 ** 31
new Set([1]).difference(setLike);

if (!called) {
return Set.prototype.difference;
}
}
return implementation;
};
23 changes: 23 additions & 0 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -493,5 +493,28 @@ module.exports = function (difference, t) {
st.end();
});

t.test('works with a set-like of certain sizes', function (st) {
var setLike = {
size: Math.pow(2, 31),
has: function () {},
keys: function () {
throw new Error('Unexpected call to |keys| method');
}
};

st.doesNotThrow(
function () { difference(new $Set([1]), setLike); },
'2**31: `keys` function is not invoked'
);

setLike.size = Infinity;
st.doesNotThrow(
function () { difference(new $Set([1]), setLike); },
'∞: `keys` function is not invoked'
);

st.end();
});

return t.comment('tests completed');
};

0 comments on commit 266d8aa

Please sign in to comment.