|
1 | 1 | const fs = require("fs"); |
| 2 | +const lodash = require("lodash"); |
2 | 3 | /** |
3 | 4 | * Looks up anagrams of a given word based on the |
4 | 5 | * word dictionary provided in the constructor. |
@@ -43,9 +44,31 @@ class AnagramService { |
43 | 44 | if (!this.wordsMap || this.wordsMap.length === 0) { |
44 | 45 | throw Error("Error: Dictionary not initialized"); |
45 | 46 | } |
| 47 | + const termCharacterMap = {}; |
| 48 | + for (const index in Array.from(term).sort()) { |
| 49 | + const character = term[index]; |
| 50 | + if (termCharacterMap[character]) { |
| 51 | + termCharacterMap[character]++; |
| 52 | + } else { |
| 53 | + termCharacterMap[character] = 1; |
| 54 | + } |
| 55 | + } |
| 56 | + const filteredWordsMapKeys = this.wordsMap.filter((word) => { |
| 57 | + const hasSameLength = word.length === term.length; |
| 58 | + const wordCharacterMap = {}; |
| 59 | + for (const index in Array.from(word).sort()) { |
| 60 | + const character = word[index]; |
| 61 | + if (wordCharacterMap[character]) { |
| 62 | + wordCharacterMap[character]++; |
| 63 | + } else { |
| 64 | + wordCharacterMap[character] = 1; |
| 65 | + } |
| 66 | + } |
| 67 | + const KeysAreEqual = lodash.isEqual(wordCharacterMap, termCharacterMap); |
46 | 68 |
|
47 | | - // TODO: The anagram lookup 🤦♂️ |
48 | | - return this.wordsMap; |
| 69 | + return hasSameLength && KeysAreEqual; |
| 70 | + }); |
| 71 | + return filteredWordsMapKeys; |
49 | 72 | } |
50 | 73 | } |
51 | 74 |
|
|
0 commit comments