Skip to content

Instantly share code, notes, and snippets.

@jmakeig
Created April 13, 2017 21:12
Show Gist options
  • Save jmakeig/c25124b24ba06c19d6261e913ae59e86 to your computer and use it in GitHub Desktop.
Save jmakeig/c25124b24ba06c19d6261e913ae59e86 to your computer and use it in GitHub Desktop.
JavaScript ES2015 Set equality
/**
*
*
* @param {Set} aaa
* @param {Set} bbb
* @param {function} [comparator]
* @returns {boolean}
*/
function equalSets(aaa, bbb, comparator = (x, y) => x === y) {
if ('function' !== typeof comparator) {
throw new TypeError(typeof comparator);
}
if (!(aaa instanceof Set) || !(bbb instanceof Set)) return false;
if (aaa.size !== bbb.size) return false;
for (const itemA of aaa) {
let hasB = false;
for (const itemB of bbb) {
hasB = comparator(itemA, itemB);
if (hasB) {
// Is this more expensive than brute force?
return equalSets(
cloneWithout(aaa, itemA),
cloneWithout(bbb, itemB),
comparator
);
}
}
if (!hasB) return false;
}
return true;
}
/**
* Clones a new set with a specific entry.
* Doesn’t modify `set`.
*
* @param {Set} set
* @param {any} entry
* @returns {Set}
* @throws {TypeError}
*/
function cloneWithout(set, entry) {
if (!(set instanceof Set)) {
throw new TypeError(String(set));
}
const clone = new Set(set);
if (undefined !== entry) {
clone.delete(entry);
}
return clone;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment