Skip to content

Commit 6a92807

Browse files
committed
Added the code to find the anagram
1 parent e1d6cc4 commit 6a92807

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

src/anagram-service.js

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
const fs = require("fs");
2+
const lodash = require("lodash");
23
/**
34
* Looks up anagrams of a given word based on the
45
* word dictionary provided in the constructor.
@@ -43,9 +44,31 @@ class AnagramService {
4344
if (!this.wordsMap || this.wordsMap.length === 0) {
4445
throw Error("Error: Dictionary not initialized");
4546
}
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);
4668

47-
// TODO: The anagram lookup 🤦‍♂️
48-
return this.wordsMap;
69+
return hasSameLength && KeysAreEqual;
70+
});
71+
return filteredWordsMapKeys;
4972
}
5073
}
5174

0 commit comments

Comments
 (0)