Created
April 13, 2017 21:12
-
-
Save jmakeig/c25124b24ba06c19d6261e913ae59e86 to your computer and use it in GitHub Desktop.
JavaScript ES2015 Set equality
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* | |
* @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