Skip to content

Instantly share code, notes, and snippets.

@kopiro
Last active February 25, 2021 14:48
Show Gist options
  • Save kopiro/771903bfc4678b765206b3b51b12f04a to your computer and use it in GitHub Desktop.
Save kopiro/771903bfc4678b765206b3b51b12f04a to your computer and use it in GitHub Desktop.
UNIQUE Permutations ES6 Generators
const permutations = function*(elements, map = new Map()) {
if (elements.length === 1) {
yield elements;
} else {
const [first, ...rest] = elements;
for (const perm of permutations(rest, map)) {
for (let i = 0; i < elements.length; i++) {
const start = perm.slice(0, i);
const rest = perm.slice(i);
const val = [...start, first, ...rest];
const key = JSON.stringify(val);
if (!map.has(key)) {
map.set(key, val);
yield val;
}
}
}
}
}
export function* permutations<T>(
elements: T[],
map: Map<string, T> = new Map(),
serializer = (val: T[]) => JSON.stringify(val)
) {
if (elements.length === 1) {
yield elements;
} else {
const [first, ...rest] = elements;
for (const perm of permutations(rest, map, serializer)) {
for (let i = 0; i < elements.length; i++) {
const start = perm.slice(0, i);
const rest = perm.slice(i);
const val = [...start, first, ...rest];
const key = serializer(val);
if (!map.has(key)) {
map.set(key, val);
yield val;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment