Skip to content

Instantly share code, notes, and snippets.

@tvler
Last active April 18, 2019 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvler/cc5b2a3f01543e1658b25ca567c078e4 to your computer and use it in GitHub Desktop.
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
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