Skip to content

Commit 1365fca

Browse files
Find anagram in JavaScript, running under node
1 parent b265bb0 commit 1365fca

File tree

4 files changed

+23995
-0
lines changed

4 files changed

+23995
-0
lines changed
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Find An Anagram
2+
3+
```
4+
node index.js apple
5+
Finding anagrams for apple
6+
[ 'a',
7+
'ale',
8+
'ape',
9+
'apple',
10+
'la',
11+
'lap',
12+
'lea',
13+
'leap',
14+
'pa',
15+
'pal',
16+
'pale',
17+
'pap',
18+
'pea',
19+
'peal',
20+
'pep',
21+
'plea',
22+
'' ]
23+
apple has 17 subanagrams. a, ale, ape, apple, la, lap, lea, leap, pa, pal, pale, pap, pea, peal, pep, plea,
24+
```
+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Code modified to work locally from https://github.com/evanchiu/alexa-anagram
2+
const fs = require('fs');
3+
const path = require('path');
4+
5+
exports.getAnagrams = function(target, callback) {
6+
getDictionary(function(err, dictionary) {
7+
if (err) {
8+
callback(err);
9+
} else {
10+
targetCountHash = getLetterCountHash(target);
11+
subanagrams = [];
12+
for (let i = 0; i < dictionary.length; i++) {
13+
if (isSubanagram(targetCountHash, getLetterCountHash(dictionary[i]))) {
14+
subanagrams.push(dictionary[i]);
15+
}
16+
}
17+
callback(null, subanagrams);
18+
}
19+
});
20+
};
21+
22+
function getDictionary(callback) {
23+
let dictionaryFile = path.join(__dirname, 'data', '6of12.txt');
24+
// console.log(dictionaryFile);
25+
fs.readFile(dictionaryFile, function(err, data) {
26+
if (err) {
27+
callback(err);
28+
} else {
29+
callback(null, data.toString().split('\n'));
30+
}
31+
});
32+
}
33+
34+
function isSubanagram(base, candidate) {
35+
for (let letter in candidate) {
36+
if (!base[letter] || base[letter] < candidate[letter]) {
37+
return false;
38+
}
39+
}
40+
return true;
41+
}
42+
43+
function getLetterCountHash(word) {
44+
let letters = word.split('');
45+
let countHash = {};
46+
for (let i = 0; i < letters.length; i++) {
47+
if (countHash[letters[i]]) {
48+
countHash[letters[i]] += 1;
49+
} else {
50+
countHash[letters[i]] = 1;
51+
}
52+
}
53+
return countHash;
54+
}
55+

0 commit comments

Comments
 (0)