garrethwills
garrethwills

Reputation: 41

Can't get two variables to concatenate

I'm a newbie, making a little exercise to practice with arrays. I've tried solving this from previous articles but none seem to have the relevant scenario.

I want to randomly generate sentences into paragraphs using phrases from an array. I got the random sentence generation part working fine.

    var ipsumText = ["adventure", "endless youth", "dust", "iconic landmark", "spontaneous", "carefree", "selvedge","on the road", "open road", "stay true", "free spirit", "urban", "live on the edge", "the true wanderer", "vintage motorcyle", "american lifestyle", "epic landscape", "low slung denim", "naturaL"];

//a simple function to print a sentence //

var sentence = function (y) { 
var printSentence = "";
for (i=0; i<7; i++) { 
    //random selection of string from array //
    var x = Math.floor(Math.random() * 20);
    printSentence += y [x] + " "; 
}
return printSentence
};

console.log(sentence(ipsumText));

But now I want to be able to add a comma or full stop to the end of the sentence.

Because each word/phrase from the array used in the sentence prints with a space after it, I need to add an extra word with a full stop or comma right after it to avoid the space between them. To do this I created an extra variable

 // create a word and full stop to end a sentence//
var addFullstop = ipsumText[Math.floor(Math.random() * ipsumText.length)] + ". ";
var addComma = ipsumText[Math.floor(Math.random() * ipsumText.length)] + ", ";

These variables work on their own how I expect. They print a random word with a comma or full stop right after them.

However now I can't work out how to get them to add to the end of the sentence. I have tried quite a few versions referencing articles here, but I'm missing something, because when I test it, I get nothing printing to the console log.

This is what I have most recently tried.

// add the sentence and new ending together //
var fullSentence = sentence(ipsumText) + addFullstop;
console.log(fullSentence)

Can someone explain why this wouldn't work? And suggest a solution to try? thanks

Upvotes: 1

Views: 118

Answers (1)

Josh
Josh

Reputation: 4806

See ES6 fiddle: http://www.es6fiddle.net/isadgquw/

Your example works. But consider a different approach which is a bit more flexible. You give it the array of words, how long you want the sentence to be, and if you want an ending to the sentence, pass in end, otherwise, just leave it out and it will not be used.

The first line generates an array of length count which is composed of random indices to be used to index into the words array. The next line maps these indices to actual words. The last line joins all of these into a sentence separated by a single space, with an optional end of the sentence which the caller specifies.

const randomSent = (words, count, end) =>
    [...Array(count)].map(() => Math.floor(Math.random() * words.length))
                     .map(i => words[i])
                     .join(' ') + (end || '')

randomSent (['one','two','x','compound word','etc'], 10, '! ')
// x x one x compound word one x etc two two!

To make it more flexible, consider making a function for each task. The code is reusable, specific, and no mutable variables are used, making it easy to test, understand, and compose however you like:

const randInt = (lower, upper) =>
    Math.floor(Math.random() * (upper-lower)) + lower

const randWord = (words) => words[randInt(0, words.length)]

const randSentence = (words, len, end) =>
    [...Array(len)].map(() => randWord(words))
                   .join(' ') + (end || '')

const randWordWithEnd = (end) => randWord(ipsumText) + end
const randWordWithFullStop = randWordWithEnd('. ')
const randWordWithComma    = randWordWithEnd(', ')

// Now, test it!
const fullSentWithEnd = randSentence(ipsumText, 8, '!!')
const fullSentNoEnd = randSentence(ipsumText, 5)
const fullSentComposed = fullSentNoEnd + randWordWithFullStop

Link again for convenience: http://www.es6fiddle.net/isadgquw/

Upvotes: 1

Related Questions