mercredi 28 octobre 2015

trouble turning file into array and then outputting object value

The goal of my application is simple:

  • Accept a random number parameter
  • Read the dictionary.txt file
  • turn that file into an array by taking each word in the file (each word is on a new line in the file)
  • push each array item created into an object and then have itself as a word property

At the point I have the object created, my aim is to get a random word from that object, for example:

outputObj[randNum].word

Which should return the word at the index I set in the randNum parameter and the value stored in its word property.

I am getting confused and have tried everything I can think of to achieve the end result.

Here is my current JS:

var fs = require('fs),
    getWordFromRandomNumber = function(randNum) {
        var output = fs.readFileSync('../dictionary/dictionary.txt', 'utf8')
            .trim()
            .split('/n')
            .map(line => line.split('/n'))
            .reduce(function(outputObj, line){
            outputObj[line] =  outputObj[line] || [];
            outputObj[line].push({
                word: line,
            });
            return outputObj[randNum].word;
        }, {});


        console.log(JSON.stringify(output, null, 2));
    }

getWordFromRandomNumber(25);

I expect this to return to me the value of outputObj[25].word but all I get is a cascade of the whole file, see here (note I am using my cmd to run the file using babel and node with the command "babel wordGenerator.js | node":

enter image description here

Any help would be much appreciated as I am all out of ideas at the moment.

Thanks, SD




Aucun commentaire:

Enregistrer un commentaire