Anagrams

Give it a word and the node will look for all the words (in a tiny DB) that are anagrams of the given one.

/**
* A tiny DB of words
*/
import words from "an-array-of-english-words";
import { createInterface } from "readline";
/**
* Opens an input interface
*/
const rla = createInterface({ input: process.stdin, output: process.stdout });
/**
* It counts the number of letters in each word
*/
const countOcurrences = (arr) =>
arr.reduce(
(acc, str) => ({
...acc,
[str]: acc[str] ? acc[str] + 1 : 1,
}),
{}
);
const hasSameLetterCount = (word1, word2) => {
const word1Count = countOcurrences(word1.split(""));
const word2Count = countOcurrences(word2.split(""));
/**
* NTala: return must be in the same line.
* the first filter is for the same amount of letters
*
*/
return (
Object.keys(word1Count).length === Object.keys(word2Count).length &&
/**
* The second filter is to check each letter in the word exist in the second one
*/
Object.keys(word1Count).every(
(letter) => word1Count[letter] === word2Count[letter]
)
);
};
const findAnagrams = (word, allWords) => {
return allWords
.filter((entry) => hasSameLetterCount(word, entry))
.filter((anagram) => anagram !== word);
};
rla.question(
`
whats the word for the anagrams?
`,
(answer) => {
console.log(findAnagrams(answer, words));
rla.close();
}
);

Source: https://www.linkedin.com/learning/learning-functional-programming-with-javascript-es6-plus/challenge-error-messages