0

I want to create random usernames. I use a list names and firstnames from a file and get one from each files randomly.

var nameList= fs.readFileSync("random-name/names.txt").toString().split("\n");
var name = nameList[Math.ceil(Math.random()*nameList.length)];

var firstnameList= fs.readFileSync("random-name/first-names.txt").toString().split("\n");
var firstname= firstnameList[Math.ceil(Math.random()*firstnameList.length)];

The problem appears when I want to concatenate them:

console.log( name);
console.log( firstname);
console.log( firstname+"-"+name);

outputs:

Brant
Jesselyn
-Brantyn

There is obviously no problem if I set the variable name and firstname statically.

3
  • 3
    Maybe there is a CR character at the end of firstname? Try to print the string lengths... Commented Nov 15, 2015 at 12:42
  • You want Math.floor instead of Math.ceil Commented Nov 15, 2015 at 12:43
  • you are also right but that is not the current problem! Commented Nov 15, 2015 at 12:43

2 Answers 2

2

The problem occurs because I splitted the file content with "\n", and there was still "\r" at the end of each names and firstnames.

Sign up to request clarification or add additional context in comments.

Comments

1

As you've noted yourself, remove \r from the input, or alternatively split on \r?\n.

Other notes:

  • Don't repeat yourself.
  • Your "random item" calculation is wrong, you should be using floor, not ceil.

How about:

function getLines(filename) {
    return fs.readFileSync(filename).toString().split(/\r?\n/);
}
Array.prototype.getRandomItem = function () {
    return this[Math.floor(Math.random() * this.length)];
};

and

var nameList = getLines("random-name/names.txt");
var name = nameList.getRandomItem();

var firstnameList = getLines("random-name/first-names.txt");
var firstname = firstnameList.getRandomItem();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.