Thursday 18 February 2016

Best way to feed .txt file into an array?

I have a .txt file without about 250k lines of English words. I'd like to be able to feed each line as a string into an array, so that I can take a base word such as "ever" and pick out the anagrams from the huge array.I've got a function that takes a target word and an array and gets the anagrams. However, I can't quite figure out how to load this local file into a huge array. Here's what I have so far:var fs = require('fs'); var readline = require('readline'); var stream = require('stream'); var instream = fs.createReadStream('/Users/myName/Documents/JavaScript/web/wordsEn.txt'); var outstream = new stream; var rl = readline.createInterface(instream, outstream); var arr = []; rl.on('line', function(line) { arr.push(line); }); rl.on('close', function() { return arr;} ); function alphabetize(word) { return word.split('').sort().join(''); } function anagrams(target, words) { var output = []; for(var i = 0; i < words.length; i++) { var word = words[i]; if(alphabetize(target) === alphabetize(word)) { output.push(word); } else continue; } return output; } But I get an error when I try to play with it in my terminal. Any suggestions as to how I can get this working?

Submitted February 18, 2016 at 08:12AM by ConfuciusBateman

No comments:

Post a Comment