Javascript - Array.repeat limitations? - javascript

I have an array and I'm looking to create a new array, composed of the original array contents repeated 3 times. For example:
var array = ["red", "green", "blue"];
newArray = ["red red red", "green green green", "blue blue blue"];
My code so far:
var triples = myArray.map(function(){
for (x = 0; x < myArray.length; x++){
return myArray[x].repeat(3);
};
});
console.log(triples);
But this only returns
triples = ["redredred", "redredred", "redredred"];
Any suggestions for a newbie?

You can build a simple function to do this:
var triples = function(xs) {
return xs.map(function(x) {
return [x,x,x].join(' ')
})
}
You can abstract it a bit more, as a transformation to use with map, and allow any number of repetitions:
var repeat = function(n) {
return function(x) {
return Array.apply(0, {length:n})
.map(function(){return x})
.join(' ')
}
}
['foo','bar','lol'].map(repeat(3))
//^ ['foo foo foo', 'bar bar bar', 'lol lol lol']

Here's an obnoxiously simple way of repeating all elements 3 times:
["red", "green", "blue"].map( [].join.bind(['',' ',' ','']) );
// == ["red red red", "green green green", "blue blue blue"]
this method also doesn't need "".repeat(), which is not universally supported yet.
another bonus: if a number, null, or other non-string sneaks in the array it won't break.
if you want it re-usable, that's easy enough:
var repeater = [].join.bind(['',' ',' ','']) ;
["red", "green", "blue"].map( repeater );
// == ["red red red", "green green green", "blue blue blue"]
[1,2,3,4,5].map( repeater );
// == ["1 1 1", "2 2 2", "3 3 3", "4 4 4", "5 5 5"]

There is no reason to use map and the loop. I guess you wanted either
var triples = myArray.map(function(str){
return str.repeat(3);
});
console.log(triples);
or
var triples = [];
for (var x = 0; x < myArray.length; x++) {
triples[x] = myArray[x].repeat(3);
}
console.log(triples);
However, as #digitalfresh mentioned in the comments, String::repeat doesn't insert the spaces, so you rather want to use (" "+…).repeat(3).slice(1) or use the functions presented by #dandavis or #elclanrs. Or, since you seem to use an Ecmascript 6 method anyway, you could do Array.from({length:3}, ()=>…).join(" ").

Related

Picking array based off of percentage and shuffling it

I've got my percentages hammered out along with my arrays. I know I need to make it so that the percentage determines WHICH array is picked, and then I need to shuffle that array to make it spit out one of the three "things". I know there's an easier/more efficient way to do this without clogging my code with a million shuffle functions to determine the "Thing" variable.
Currently, it's not working (spits out "undefined") but it's left my scratching my head as I'm not sure what the issue is, along with wanting to streamline it.
The entire point of the code is to pick an array based on the rolled percentage, randomize that array, and spit back out the value it got from shuffling it.
Current absolute dumpster-fire I'm working with:
function generate(){
var tierOne = ["thing one", "thing two", "thing three"]
var tierTwo = ["thing four", "thing five", "thing six"]
var tierThree = ["thing seven", "thing eight", "thing nine"]
var tierFour = ["thing ten", "thing eleven", "thing twelve"]
var tierFive = ["thing thirteen", "thing fourteen", "thing fifteen"]
var percent = r();
if (percent >= 0 && percent < 25) {
shuffle(tierOne)
thing = tierOne;
return thing[0];
} else if (percent >= 25 && percent < 36) {
shuffle(tierTwo)
thing = tierTwo;
return thing[0];
} else if (percent >= 36 && percent < 60) {
shuffle(tierThree)
thing = tierThree;
return thing[0];
} else if (percent >= 60 && percent < 76) {
shuffle(tierFour)
thing = tierFour;
return thing[0];
} else {
shuffle(tierFive)
thing = tierFive;
return thing[0];
}
}
function r() {
Math.floor(Math.random() * 100) + 1;
return Math.floor(Math.random() * 100) + 1;
}```
First, I don't think there's any need to set up different arrays, then use that if-then-else logic where you compare the percentage to a range of values. Just make an array of arrays and use the index to return the one to shuffle. That also means that unless you really need the number from 1-100 for something else, then you should probably just generate a random number between 0 and 4. Assuming you need the percentage I left it in and just scale it to between 0 and 4.
I probably wouldn't have separated the shuffle logic from the generate function either, but I left it separate so you could more easily implement the shuffle logic you want. I don't believe there is a built in shuffle function in js like there is in some other languages, so you are going to have to have a shuffle function. Here is a thread on shuffling, and I shamelessly stole the shuffle function I included from it. Not saying this is the best one, just looked nifty. There is plenty of discussion in that post about the different implications of different shuffling algorithms.
How to randomize (shuffle) a JavaScript array?
console.log(generate());
function generate(){
const raw = [
["thing one", "thing two", "thing three"],
["thing four", "thing five", "thing six"],
["thing seven", "thing eight", "thing nine"],
["thing ten", "thing eleven", "thing twelve"],
["thing thirteen", "thing fourteen", "thing fifteen"]
];
var percent = Math.floor(Math.random() * 100) + 1;
var i = Math.ceil(percent/20)-1;
return shuffle(raw[i])[0];
}
function shuffle(unshuffled){
return unshuffled
.map((value) => ({ value, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ value }) => value)
;
}
Your shuffle routine should probably return a new array with the results.
You need to declare thing, and not use a global variable.
if (percent >= 0 && percent < 20) {
const thing = shuffle(tierOne)
return thing[0];
}
or
let thing
if (percent >= 0 && percent < 20) {
thing = shuffle(tierOne)
return thing[0];
}

JavaScript string count loop misunderstanding

I am having trouble with a basic task. I need to write a JavaScript program that contains an array of at least five strings, loops through the array, and calls a function for each item; this function should check to see how long the string is:
If the string is less than four characters, print the phrase "Less Than Four"
If equal to four characters, print "Exactly Four"
If longer than four, print "More Than Four"
I have tried so many things, but feel like I am looking in the wrong spots. I understand this is basic but I cant seem to wrap my head around this...
My Code right now:
var colors = ["teal", "violet", "silver", "green", "red", "purple"];
var count;
for (count = 0; count < colors.length; count++) {
console.log(colors[count]);
}
if (colors > 4) {
console.log("greater than 4");
}
if (colors < 4) {
console.log("less than 4");
}
if (colors = 4) {
console.log("is equal to 4");
}
Arrays have built-in methods for looping that allow a callback function to be executed upon each iteration of the loop. In your scenario, since you are just needing to examine the string, the .forEach() method is probably the most appropriate.
In the function, you only need a simple if/then/else statement to determine which message to print.
var colors = ["teal", "violet", "silver", "green", "red", "purple"];
colors.forEach(function(color){
if(color.length < 4){
console.log(color + " has less than 4 characters.");
} else if (color.length === 4) {
console.log(color + " has 4 characters.");
} else {
console.log(color + " has more than 4 characters.");
}
});
Newer versions of JavaScript support for..of syntax
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
for (const c of colors)
{ if (c.length > 4)
console.log(c, "greater than 4")
else if (c.length < 4)
console.log(c, "less than 4")
else
console.log(c, "equal to 4")
}
// teal equal to 4
// violet greater than 4
// silver greater than 4
// green greater than 4
// red less than 4
// purple greater than 4
You should separate the concerns of the loop and the length check using a function -
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
const checkLength = str =>
{ if (str.length > 4)
return "greater than 4"
else if (str.length < 4)
return "less than 4"
else
return "equal to 4"
}
for (const c of colors)
console.log(c, checkLength(c))
// teal equal to 4
// violet greater than 4
// silver greater than 4
// green greater than 4
// red less than 4
// purple greater than 4
JavaScript is a multi-paradigm language, so it supports writing the same program in a wide variety of styles -
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
const checkLength = str =>
{ if (str.length > 4)
console.log(`${str} is greater than 4`)
else if (str.length < 4)
console.log(`${str} is less than 4`)
else
console.log(`${str} is equal to 4`)
}
colors.forEach(checkLength)
// teal equal to 4
// violet greater than 4
// silver greater than 4
// green greater than 4
// red less than 4
// purple greater than 4
JavaScript support for expressions is quite good too, removing the need for imperative-style keywords like if, else, switch, for, while, do and even return -
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
const checkLength = x =>
x.length > 4 // if ...
? `${x} is greater than 4`
: x.length < 4 // else if ...
? `${x} is less than 4`
: `${x} is equal to 4` // else
console.log(colors.map(checkLength))
// [ "teal is equal to 4"
// , "violet is greater than 4"
// , "silver is greater than 4"
// , "green is greater than 4"
// , "red is less than 4"
// , "purple is greater than 4"
// ]
Call a function on every element and check the length inside an if-else block
var colors = ["teal", "violet", "silver", "green", "red", "purple"];
var count;
for (count = 0; count < colors.length; count++) {
console.log(colors[count]);
stringLength(colors[count]);
}
function stringLength(string) {
if (string.length > 4) {
console.log("greater than 4");
} else if (string.length < 4) {
console.log("less than 4");
} else {
console.log("is equal to 4");
}
}
You need to put the if statements inside the curly braces of the for loop, so for every color it will run through all the if conditions and print if it matches.
A more idiomatic way of doing what you're currently trying to do is to implement the logic within the body of a forEach function, which is part of the Array object's prototype
var colors = ["teal", "violet", "silver", "green", "red", "purple"];
colors.forEach(function(currentColorToCheck) { //currentColorToCheck is a temporary variable that the forEach function gives you (1 for every item of colors Array)
if (currentColorToCheck.length > 4) { // we use the .length function (part of String prototype and Array prototype) to get the length of the string
console.log("greater than 4");
}
if (currentColorToCheck.length < 4) {
console.log("less than 4");
}
if (currentColorToCheck.length === 4) { // here for an equality comparison, use === instead of =
console.log("is equal to 4");
}
})
The forEach is a more convenient way to express "Iterate over values of an Array". You can look at the documentation for some further guidance.
As a sidenote, there's tons of prototype (builtin) functions for every JavaScript type (Object, Array, String, Number, Date, Math, etc.) which you might want to study in your spare time. Mozilla Developer Network has great resources for that.

Finding the decimal exponent based on the index of a for-loop

The user chooses a number and then d3.js should display as many circles.
I have an array that is used to assigned color to the circles:
var color =["red","blue", "yellow", "orange",....., ]
● If the user choose 593, the first 500 circle should be red (color[0]) , the next 90 should be blue (color[1]) and the last 3 (color[2]) should be yellow Because
593= 500+90+3 = 5*10^2+9*10^1+3*10^0
or
with
var number = 593
var number_as_array = number.toString().split('');
Then
593 = 5*number_as_array[0]*10^number_as_array.length-0-1 + 9*number_as_array[1]*10^number_as_array.length-1-1+ 3*number_as_array[2]*10^number_as_array.length-2-1
● If the user choose 4168 the first 4000 circle should be red, the next 100 should be blue, the next 60 yellow and the last 8 orange
To assign the color to each circle I use to create an array of JS object build with a for loop
var data=[]
for (index =0; index< number; index++){
circle= {};
circle.cx = circle_x;
circle.cy = circle_y;
circle.color = color[????]
data.push(circle);
How can I assign the color to circle.color based on the condition above ?
Not to diminish from the other answer, here's an alternative approach.
Taking a given total number of circles, it checks to see how many significant digits of the total are required (rounding down) so that any given index is less than rounded total.
I'm not sure if that makes complete sense, so I'll use an example:
If there are 132 circles in total:
Indexes 0 through 99 will be less than 100 (132 rounded down with one significant digit).
Indexes 100 through 129 will be less than 130 (132 rounded down with two significant digits).
Indexes 130 and 131 will be less than 132 (132 with all significant digits).
Here's a quick demonstration (rows are 50 circles across):
var svg = d3.select("body")
.append("svg")
.attr("width",510)
.attr("height",510);
var n = 377;
var color = d3.scaleOrdinal()
.range(["steelblue","orange","crimson","lawngreen","pink"])
var digits = Math.floor(Math.log10(n));
var circles = svg.selectAll("circle")
.data(d3.range(n))
.enter()
.append("circle")
.attr("cx",function(d,i) { return i%50 * 10 + 5 })
.attr("cy",function(d,i) { return Math.floor(i/50) * 10 + 5 })
.attr("r",5)
.attr("fill", function(d,i) {
var exp = digits;
while (i < Math.floor(n/Math.pow(10,digits-exp))*Math.pow(10,digits-exp)) {
exp--;
}
return color(exp);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
var color = ["red","orange", "yellow", "green", "blue", "indigo", "violet"];
var circleCount = "4192"; // use string
var length = circleCount.length;
var counter = [];
for (var i = 0; i < length; i++) {
var digit = circleCount.substring(i, i+1);
var exponent = length - i - 1;
var number = digit * Math.pow(10, exponent);
counter.push(number); // might have to use .unshift instead of .push
}
console.log(counter);
for (var i = 0; i < counter.length; i++) {
for (var j = 0; j < counter[i]; j++) {
drawCircle(color[i]);
}
}
This is a perfect case for using D3's Threshold Scales: you give it N numbers where you want breaks between the colors, and N+1 colors to return for any input value. Here is the example from the docs:
var color = d3.scaleThreshold()
.domain([0, 1])
.range(["red", "white", "green"]);
color(-1); // "red"
color(0); // "white"
color(0.5); // "white"
color(1); // "green"
color(1000); // "green"
So the challenge for your case is how to convert (for instance) your example input of 593 into the array of the two numbers [500, 590]:
var sinput = 593 + ""; // make the input a string
var digits = sinput.split("").slice(0, -1); // use all digits but the last one
var breaks = digits.map((d, i, a) =>
+(a.slice(0, i+1).join("")) * Math.pow(10, a.length-i)
);
var colors = ["red", "blue", "yellow", "orange"];
var tScale = d3.scaleThreshold()
.domain(breaks)
.range(colors);
Anything < 500 maps to "red", from 500 - 589 maps to "blue", and ≥ 590 maps to "yellow". The additional range color ("orange") is not used, unless a 4-digit number is used as input.
Note: this logic assumes the input number will have at least 2-digits.
You can now assign the color at the time of creating the circle -- rather than pre-populating it in the data array -- using syntax like .attr("color", (d, i) => tScale(i))
The other approaches seem overly complex. You can split the number into its digits, then create the required 10^digitIndex circles with colour based on the index. I've included a line to check that the number isn't too big.
function mapColors(num) {
var color =['red','blue', 'yellow', 'orange'];
// If the number is longer than the color array, return undefined
if ((''+num).length > color.length) return;
return (''+num).split('').reduce(function (acc, n, i, arr) {
for (var j=n*Math.pow(10, arr.length-i-1); j; --j) {
acc.push({'color':color[i]});
// Add more circle properties here
}
return acc;
}, []);
}
console.log(mapColors(23));

Page search and textbox autofill with javascript in Tampermonkey

I am trying to write a script in Grease/Tampermonkey which will search a webpage for an question, and then fill in the textbox with the correct answer.
This is what I've come up with so far:
//There are 12 options in each array
var questions = ["fourth letter", "grass", "6x4", "NFL team", "OSU Buckeys", "35 + 15", "Yellow + Blue", "LeBron James", "Lassie", "2x9", "9x10"];
var answers = ["s", "green", "nut", 24, "Bengals", "gray", 50, "green", 23, "dog", 18, 90];
var answer = 0;
var position = 0;
var found = false;
//When the window loads, the function will trigger the While loop, which will run as long as found is false.
//The While loop triggers the For loop, which runs until the If statement has found the question.
//The For loop will run a number of times equal to the number of variables in the questions array.
//The if statement searches the webpage for each consecutive variable in the questions array until it finds a match.
//When the if statement finds a match, it notes which variable in the questions array matched, and sets found to true which should trigger the end of the while loop.
window.onload = function () {
while (found) {
for (var i = 0;i<=questions.length;i++) {
if (document.body.innerHTML.toString().indexOf(questions[i])) > -1 {
position = i;
found = true;
} else {
console.log ("No answer was found");
};
};
};
};
//Once the While loop has completed, this fills the textbox on the webpage with the answer
document.getElementById("humanverify\[input\]").innerHTML = answers[position];
Tampermonkey indicates that the code is running. However, the textbox isn't filling. I am new to Javascript, and have been piecing together bits of code and knowledge over the last week.
found is false initially hence the while loop will never executed.
try this
var questions = ["fourth letter", "grass", "6x4", "NFL team", "OSU Buckeys", "35 + 15", "Yellow + Blue", "LeBron James", "Lassie", "2x9", "9x10"];
var answers = ["s", "green", "nut", 24, "Bengals", "gray", 50, "green", 23, "dog", 18, 90];
var answer = 0;
var position = 0;
var found = false;
window.onload = function () {
for (var i = 0;i<=questions.length;i++) {
if (document.body.innerHTML.toString().indexOf(questions[i]) > -1) {
position = i;
found = true;
break;
}
}
if(found){
document.getElementById("humanverify\[input\]").innerHTML = answers[position];
}
else{
console.log ("No answer was found");
}
}
I've been fiddling with it all day, and came up with a functional result that satisfies all my needs. Here is the result:
var answers = ["s", "green", "nut", 24, "bengals", "gray", 50, "green", 23, "dog", 18, 90];
var questions = ['The fourth letter in the word "Reds" is?','What color is grass?','A buckeye is a what?',"What's 6x4?",'The NFL team in Cincinnati is called the?','The OSU Buckeys are Scarlet and?','35 + 15 is?','Yellow + Blue is?','LeBron James wears #?','Lassie was a what?','2x9 is what?',"What's 9x10?"];
var question = document.getElementsByClassName('description')[0].innerText;
var found = 0;
var answer = 0;
//browses questions variable for match to question variable, then assigns the correlating index to found, and assigns the answer to the answer variable, as pulled from the answers variable
for (var find = 0; find <= questions.length; find++) {
if (question === questions[find]) {
found = find;
answer = answers[found];
}
}
//checks the assigned radio, fills the textbox with the answer, and clicks the Vote button
var submit = function (){
document.getElementsByName('polloptionid')[3].checked = true;
document.getElementById("humanverify").value = answer;
document.getElementsByName("vote")[0].click();
}
submit();
//allows for a slight delay so that the page can load before cycling through script again
var reload = function () {
location.reload();
}
setTimeout(reload, 3000);

First Javascript program. What am I doing wrong?

I have finally gotten around to creating my first little practice program in Javascript. I know it's not elegant as it could be. I have gotten most of this code to work, but I still get an "undefined" string when I run it a few times. I don't know why. Would someone be kind enough to explain to me where this undefined is coming from?
var work = new Array();
work[1] = "product design";
work[2] = "product system design";
work[3] = "product social media post x5";
work[4] = "product Agent Recruitment system design";
work[5] = "product profile system design";
work[6] = "product Agent testing design";
work[7] = "product customer support";
work[8] = "product promotion";
var course = new Array();
course[1] = "javascript";
course[2] = "mandarin";
course[3] = "javascript practical-Code Academy";
course[4] = "javascript practical-learn Street";
course[5] = "mandarin practical-memrise";
course[6] = "new stuff with audiobooks";
var activity = new Array();
activity[1] = "listen to podcasts";
activity[2] = "chat online";
activity[3] = "Exercise";
activity[4] = "take a walk";
activity[5] = "call a friend";
var picker1 = Math.floor(Math.random()*3+1);
var picker2 = Math.floor(Math.random()*work.length+1);
var picker3 = Math.floor(Math.random()*course.length+1);
var picker4 = Math.floor(Math.random()*activity.length+1);
var group_pick = function(){
if(picker1 === 1){
return "Time to work on ";
} else if(picker1 === 2){
return "Time to learn some ";
} else if (picker1 === 3){
return "Lets relax and ";
} else {
return "error in group_pick";
}
};
var item_pick = function() {
if (picker1 === 1) {
return work[picker2] ;
} else if (picker1 === 2) {
return course [picker3] ;
} else if (picker1 === 3) {
return activity[picker4] ;
} else {
return "error in item_pick";
}
};
var task = group_pick() + item_pick();
document.write(task);
Array's start with an index of zero. When you assign a value to the 1 index, a 0 index is created you, with no value (undefined).
var arr = new Array();
arr[1] = 'hi!';
console.log(arr); // [undefined, "hi!"]
console.log(arr.length) // 2
Length is 2, check that out. You thought you had one item in that array but length is 2.
Usually it's easier to not manage the array indices yourself. And the array literal syntax is usually preferred for a number of reasons.
var arr = [];
arr.push('hi!');
console.log(arr); // ["hi!"]
console.log(arr.length) // 1
Or just create the array with the items in it directly, very handy.
var arr = [
"hi",
"there!"
];
console.log(arr); // ["hi", "there"]
console.log(arr.length) // 2
Once you are making the arrays properly, you can get a random item with simply:
var arr = ['a','b','c'];
var index = Math.floor(Math.random() * arr.length);
console.log(arr[index]); // "a", "b" or possibly "c"
This works because var index will be calculated by a random value of between 0.0 and up to but not including 1.0 times 3 (the length of the array). Which can give you a 0, 1 or a 2.
So this arr right here, has 3 items, one at 0, one at 1, and one at 2.
Learning to address arrays from zero can be mentally tricky. You sort of get used to it. Eventually.
A working example using these tips here: http://jsfiddle.net/du5Jb/
I changed how the arrays are declared, and removed the unneeded +1 from var pickerX calculations.
The problem is that the .length attribute for arrays counts the number of elements in the array starting from zero. So for example activity has elements 1 through 5, so according to Javascript the .length is actually 6. Then your random number calculation will choose a number from 1 through 7, past the end of the array. This is where the undefined comes from.
You can fix this by starting your index numbering at 0 instead of 1, so activity would have elements 0 through 4, with a .length of 5. Also remove the +1 from your choice calculations.
When you use your "pickers", you don't want to have the +1 inside of the `Math.floor functions.
Consider this array:
var array = [ "one", "two", "three" ];
array.length; // 3
The length is 3 -- makes sense, there are 3 items inside.
But arrays are zero-based.
array[0]; // "one"
array[1]; // "two"
array[2]; // "three"
array[3]; // undefined
So when you add that + 1, you're:
a) making it impossible to pick the first thing in the array
b) making it possible to pick a number that is exactly 1 higher than the last element in the array (undefined)
The problem here as i see it is that when you generate your random variables you're doing PickerX + 1...
So the right way to do it would be PickerX without the +1.
Also Off topic you shouldn't use if commands, try using switch case...
Here's the fixed code-
var work = new Array()
work[0] = "product design";
work[1] = "product system design";
work[2] = "product social media post x5";
work[3] = "product Agent Recruitment system design";
work[4] = "product profile system design";
work[5] = "product Agent testing design";
work[6] = "product customer support";
work[7] = "product promotion";
var course = new Array();
course[0] = "javascript";
course[1] = "mandarin";
course[2] = "javascript practical-Code Academy";
course[3] = "javascript practical-learn Street";
course[4] = "mandarin practical-memrise";
course[5] = "new stuff with audiobooks";
var activity = new Array();
activity[0] = "listen to podcasts";
activity[1] = "chat online";
activity[2] = "Exercise";
activity[3] = "take a walk";
activity[4] = "call a friend";
var picker1 = Math.floor(Math.random() * 3 +1 );
var picker2 = Math.floor(Math.random() * work.length );
var picker3 = Math.floor(Math.random() * course.length );
var picker4 = Math.floor(Math.random() * activity.length );
var group_pick = function(){
switch(picker1){
case 1:
return "Time to work on ";
case 2:
return "Time to learn some ";
case 3:
return "Lets relax and ";
default:
return "error in group_pick";
}
};
var item_pick = function() {
switch(picker1){
case 1:
return work[picker2] ;
case 2:
return course [picker3] ;
case 3:
return activity[picker4] ;
default:
return "error in item_pick";
}
};
var task = group_pick() + item_pick();
document.write( task );​
Don't work so hard. Zero is your friend. Let's go golfing...
var work = [
"product design", "product system design",
"product social media post x5",
"product Agent Recruitment system design",
"product profile system design",
"product Agent testing design",
"product customer support", "product promotion",
], course = [
"javascript", "mandarin",
"javascript practical-Code Academy",
"javascript practical-learn Street",
"mandarin practical-memrise", "new stuff with audiobooks",
], activity = [
"listen to podcasts", "chat online", "Exercise",
"take a walk", "call a friend",
];
function rint(cap) {
return (Math.random() * cap) | 0;
}
function pick(item) {
switch (item) {
case 0: return "Time to work on " +
work[ rint(work.length) ];
case 1: return "Time to learn some " +
course[ rint(course.length) ];
case 2: return "Lets relax and " +
activity[ rint(activity.length) ];
default: return "error";
}
}
document.write(pick(rint(3)) + '<br>');

Categories

Resources