Skip to content

Instantly share code, notes, and snippets.

@figloalds
Last active July 18, 2019 15:01
Show Gist options
  • Save figloalds/e59185f4ddc925d8644565748751a209 to your computer and use it in GitHub Desktop.
Save figloalds/e59185f4ddc925d8644565748751a209 to your computer and use it in GitHub Desktop.
const getAnagrams = (str) => {
if(str.length === 1) {
return [str];
}
let anagrams = [];
for(let i = 0; i < str.length; i++) {
let newStr = Array.from(str).filter(Boolean);
let thisChar = newStr.splice(i, 1);
newStr = newStr.join('');
const subAnagrams = getAnagrams(newStr);
subAnagrams.forEach(anagram=> {
anagrams.push(thisChar + anagram);
})
}
return Array.from(new Set(anagrams));
};
// getAnagrams('1211')
// -> [ '1211', '1121', '1112', '2111' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment