Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
},
"homepage": "https://github.com/MoveInc/coding_exercise#readme",
"dependencies": {
"express": "^4.17.1"
"express": "^4.17.1",
"lodash": "^4.17.21"
},
"devDependencies": {
"eslint": "^7.22.0",
Expand Down
45 changes: 33 additions & 12 deletions src/anagram-service.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
const fs = require('fs');

const fs = require("fs");
const lodash = require("lodash");
/**
* Looks up anagrams of a given word based on the
* Looks up anagrams of a given word based on the
* word dictionary provided in the constructor.
*/
class AnagramService {

/**
* Creates an AnagramService instance
* @param {string} dictionaryFilePath Path to the dictionary file
*/
constructor(dictionaryFilePath) {
this.dictionaryFilePath = dictionaryFilePath;
this.wordsMap = new Map();
this.wordsArray = [];
}

/**
Expand All @@ -26,10 +25,10 @@ class AnagramService {
return reject(err);
}

const lines = data.toString().split('\n');
const lines = data.toString().split("\n");

lines.forEach((line) => {
this.wordsMap.set(line.toLowerCase(), [line]);
this.wordsArray.push(line.toLowerCase().trim());
});
return resolve(this);
});
Expand All @@ -38,16 +37,38 @@ class AnagramService {

/**
* Returns all anagrams for the given term
* @param {string} term The term to find anagrams for
* @param {string} term The term to find anagrams for
* @returns A string[] of anagram matches
*/
async getAnagrams(term) {
if (!this.wordsMap || this.wordsMap.size === 0) {
throw Error('Error: Dictionary not initialized');
if (!this.wordsArray || this.wordsArray.length === 0) {
throw Error("Error: Dictionary not initialized");
}
const termCharacterMap = this.getCharacterMap(term);

const filteredWordsMapKeys = this.wordsArray.filter((word) => {
const hasSameLength = word.length === term.length;
if (!hasSameLength) return false;
const wordCharacterMap = this.getCharacterMap(word);
const MapsAreEqual = lodash.isEqual(wordCharacterMap, termCharacterMap);

return hasSameLength && MapsAreEqual;
});

return filteredWordsMapKeys;
}

// TODO: The anagram lookup 🤦‍♂️
return this.wordsMap.get(term);
getCharacterMap(word) {
const map = {};
for (const index in Array.from(word).sort()) {
const character = word[index];
if (map[character]) {
map[character]++;
} else {
map[character] = 1;
}
}
return map;
}
}

Expand Down