Last active
October 18, 2016 05:13
-
-
Save YanivHaramati/884b77776d207ce0f13f6b327431d6e7 to your computer and use it in GitHub Desktop.
Map a phone number to potential words. This part produces all possible combinations.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var digits = {2: ['a', 'b', 'c'], 3: ['d', 'e', 'f'], 4: ['g','h','i'], 5: ['j','k','l'], 6: ['m','n','o'], 7:['p', 'q', 'r', 's'], 8: ['t','u','v'], 9: ['x','y','z']}; | |
function crossProduct(sets) { | |
var r = sets.reduce((p,c) => { | |
return p.map(x => { | |
return c.map(y => { | |
return x.concat(y); | |
}) | |
}).reduce((prev,cur) => { return prev.concat(cur) },[]) | |
}, [[]]).map(s => s.join('')); | |
return r; | |
} | |
function getSets(number) { | |
return number.split('').map(n => (digits[n]) ? digits[n] : []) | |
.filter(s => s.length); | |
} | |
module.exports = { | |
getCombos: number => { | |
var sets = getSets(number); | |
return crossProduct(sets); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// usage: node numberAnalyzer.js 4243 | |
// output: [ 'gage', 'ibid' ] | |
var digitConverter = require('./combos'); | |
var natural = require("natural"); | |
var fs = require("fs"); | |
// assumes that you have a '\n'-separated english dictionary file. | |
// which you can get from a number of places... | |
const dictionary = "dictionary/en_wordlist.txt"; | |
const number = process.argv[2]; | |
var trie = new natural.Trie(false); | |
var loadDictionary = new Promise((resolve, reject) => { | |
fs.readFile(dictionary, {"encoding":"ascii"}, (err, data) => { | |
if (err) reject(err); | |
else resolve(data); | |
}); | |
}); | |
loadDictionary.then(data => { | |
var words = data.split("\n").map(w => w.trim()) | |
.filter(w => w.length <= 10); | |
trie.addStrings(words); | |
var combos = digitConverter.getCombos(number); | |
var words = combos.filter(w => trie.contains(w)); | |
if (words.length) { | |
console.log(words); | |
} else { | |
console.log('no matches.'); | |
} | |
}).catch(err => { | |
console.err(err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
node numberAnalyzer.js 3878
[ 'dust' ]