Last active
February 1, 2021 14:48
-
-
Save mabhub/d4c6495466b2b9541476c166c8dfff48 to your computer and use it in GitHub Desktop.
Anagrams
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
/** | |
* 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