Last active
April 18, 2019 15:58
-
-
Save tvler/cc5b2a3f01543e1658b25ca567c078e4 to your computer and use it in GitHub Desktop.
A variadic function to see if any number of unsorted arrays all have the same values
This file contains 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
const areUnsortedArraysEqual = (...arrs) => { | |
const everyEqual = ([first, ...arr], isEqual) => | |
arr.every(item => isEqual(first, item)); | |
return ( | |
everyEqual(arrs, (first, arr) => arr.length === first.length) && | |
everyEqual( | |
arrs.map(arr => | |
arr.reduce( | |
(map, item) => map.set(item, (map.get(item) || 0) + 1), | |
new Map() | |
) | |
), | |
(first, map) => | |
[...new Set([...first.keys(), ...map.keys()])].every( | |
item => first.get(item) === map.get(item) | |
) | |
) | |
); | |
}; | |
console.table( | |
Object.assign( | |
{}, | |
...[ | |
[[1, 2]], // true | |
[[1, 2], [1, 2]], // true | |
[[1, 2], [1, 2], [1, 2]], // true | |
[[1, 2], [2, 1]], // true | |
[[1, 1, 2], [1, 2, 1]], // true | |
[[1, 2], [1, 2, 3]], // false | |
[[1, 2, 3, 4], [1, 2, 3], [1, 2]], // false | |
[[1, 2, 2], [1, 2]], // false | |
[[1, 1, 2], [1, 2, 2]], // false | |
[[1, 2, 3], [1, 2], [1, 2, 3]] // false | |
].map(arrs => ({ | |
[arrs | |
.map(arr => `[${arr.join(", ")}]`) | |
.join(", ")]: areUnsortedArraysEqual(...arrs) | |
})) | |
) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment