Taylor Taylor - 3 months ago 30
Javascript Question

Compressing JavaScript random sentence generator code

I'm trying to make a generator that creates a semi-random sentence based on pulling variables from arrays of different words at a randomly determined index, and then removing that word from the array to make sure that there's no repeats.

It works, but not in a way that's easy to build off of. Every time I want to pull from an array that's already been pulled from in the same line, the script just stops.



document.getElementById("button").onclick = function() {
genContent();
};

function genContent() {
var content = "";
lists();
// --- what works ---
content += r(person).concat(" ", r(verb), "ed ");
content += r(person).concat(", so ");
content += r(person).concat(" is ", r(verb), "ing ");
content += r(person);

// --- what I want to condense it down to ---
// content += r(person).concat(" ", r(verb), "ed ", r(person), ", so ", r(person), " is ", r(verb), "ing ", r(person));


document.getElementById("output").innerHTML = content.charAt(0).toUpperCase() + content.slice(1);
};

function r(array) {
random = Math.floor(Math.random() * array.length);
value = array[random];
array.splice(random, 1);
return value;
};

function lists() {

person = ["Grace", "Jared", "Suzy", "Tommy"];
verb = [
"answer", "ask", "block", "call",
"delay", "expect", "follow", "greet",
"help", "inform", "join", "kick",
"label", "mark", "need", "order",
"pick", "question", "request", "signal",
"trick", "visit", "warn"];
};

<div>
<textarea id="output" output="" rows="8" style="width:50%; min-width:285px;" readonly="readonly">
Click the button to generate a sentence.
</textarea>
<br>
<input type="button" value="Make content" id="button">
</div>





(jsfiddle link because it's easier to edit)

Any ideas on how to achieve something along the lines of the commented out code(line 15)?

Answer

is it just that concat is making this very messy? You can do this:

content = r(person) + " " + r(verb) + "ed " + r(person) + ", so "
    + r(person) + " is " + r(verb) + "ing " + r(person);

You could also use an array join, which is kinda nice since you can insert any character you want in between the elements, and you could use push() to build the array.

content = [r(person), " ", r(verb), "ed ", r(person), "
    , so ", r(person), " is ", r(verb), "ing ", r(person)];

content = content.join("");