Skip to content

Instantly share code, notes, and snippets.

@mabhub
Last active February 1, 2021 14:48
Show Gist options
  • Save mabhub/d4c6495466b2b9541476c166c8dfff48 to your computer and use it in GitHub Desktop.
Save mabhub/d4c6495466b2b9541476c166c8dfff48 to your computer and use it in GitHub Desktop.
Anagrams
/**
* Return a copy of `array` without element at `index`
*/
const punch = (array = [], index) => {
const copy = array.slice();
copy.splice(index, 1);
return copy;
};
const getAnagrams = (word = '', dedup = true) => {
const asString = typeof word === 'string';
const letters = [...word];
const anagrams = [];
letters.forEach((letter, i) => {
const rest = getAnagrams(punch(letters, i));
if (rest.length) {
rest.forEach((restLetter) =>
anagrams.push(
asString
? [letter, ...restLetter].join('')
: [letter, ...restLetter]
));
return;
}
anagrams.push(letter);
});
return dedup
? Array.from(new Set(anagrams))
: anagrams;
}
console.log(getAnagrams('xyzz'));
console.log(getAnagrams('xyzz', false));
console.log(getAnagrams(['x', 'y', 'z', 'z']));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment