Why is new RegEx not working properly - javascript

For some reason…
When ever I try to get the Object.keys from replace.letters and use the Object.keys in a new RegExp joined by |…
The new RegExp only recognize some of the Object.keys but not all of them. I need the RegEx to dynamically create itself.
If I place a static RegExp in… It works perfectly fine.
Demo does not work properly
Demo works perfectly but I have to force the Regex to know what to look for
replace = {
letters: {
a: {
after: ["til"]
},
b: {
because: ["bec"]
},
c: {
cool: ["chill"]
},
e: {
energy: ["en"]
},
h: {
light: ["look"]
},
i: {
keen: ["ok"]
},
r: {
roll: ["rock"]
},
s: {
ship: ["skip"]
},
t: {
trip: ["tip"]
}
}
}
sentence = [
"If you want a cookie, eat your dinner.",
"As soon as you enter the house, change clean your room and mop the floor.",
"So long as I'm king, I will ensure your safty.",
"Change the curtains, after house is painted.",
"Change the curtains, by the time that we are headed.",
"Assuming that you are a good person, hold my beer.",
"Reject the offer, even if I'm not there.",
"Reject the offer, zoom I'm not there.",
"By the time the bus gets here, the show will be over with.",
"Choose a random number.",
"Try not to mess this, that and those up.",
"Change a random number, pick a color, and put it in jason's house.",
"Zoom, fix and lower the bar.",
"Don't change the house.",
"Create a playground.",
"While you were gone, I changed the lockes",
"Before I stop the car, can you get my wallet."
]
let objects_letters = Object.keys(replace.letters).join('|')
let letters_RegEx = new RegExp('^(' + objects_letters + ')', 'gi')
console.log(letters_RegEx)//This isn't working properly.
for (var i = 0; i < sentence.length; i++) {
let $this = sentence[i]
let commaKey = /,/g.test($this)
let if_While_Key = /^(If|While)/gi.test($this)
//Here is the problem
let letterKey = letters_RegEx.test($this)
//Here is the problem
if (commaKey) {
if (if_While_Key) {}
if (letterKey) {
$('body').append($this + '<br>');
} else {}
} else {}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
replace = {
letters: {
a: {
after: ["til"]
},
b: {
because: ["bec"]
},
c: {
cool: ["chill"]
},
e: {
energy: ["en"]
},
h: {
light: ["look"]
},
i: {
keen: ["ok"]
},
r: {
roll: ["rock"]
},
s: {
ship: ["skip"]
},
t: {
trip: ["tip"]
}
}
}
sentence = [
"If you want a cookie, eat your dinner.",
"As soon as you enter the house, change clean your room and mop the floor.",
"So long as I'm king, I will ensure your safty.",
"Change the curtains, after house is painted.",
"Change the curtains, by the time that we are headed.",
"Assuming that you are a good person, hold my beer.",
"Reject the offer, even if I'm not there.",
"Reject the offer, zoom I'm not there.",
"By the time the bus gets here, the show will be over with.",
"Choose a random number.",
"Try not to mess this, that and those up.",
"Change a random number, pick a color, and put it in jason's house.",
"Zoom, fix and lower the bar.",
"Don't change the house.",
"Create a playground.",
"While you were gone, I changed the lockes",
"Before I stop the car, can you get my wallet."
]
let objects_letters = Object.keys(replace.letters).join('|')
let letters_RegEx = new RegExp('^(' + objects_letters + ')', 'gi')
console.log(letters_RegEx)//This isn't working properly.
for (var i = 0; i < sentence.length; i++) {
let $this = sentence[i]
let commaKey = /,/g.test($this)
let if_While_Key = /^(If|While)/gi.test($this)
//Here is the problem
let letterKey = /^(a|b|c|e|h|i|r|s|t)/gi.test($this)
//Here is the problem
if (commaKey) {
if (if_While_Key) {}
if (letterKey) {
$('body').append($this + '<br>');
} else {}
} else {}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Your problem is your RegExp Flags
Change
let letters_RegEx = new RegExp('^(' + objects_letters + ')', 'gi')
to
let letters_RegEx = new RegExp('^(' + objects_letters + ')', 'i')
replace = {
letters: {
a: {
after: ["til"]
},
b: {
because: ["bec"]
},
c: {
cool: ["chill"]
},
e: {
energy: ["en"]
},
h: {
light: ["look"]
},
i: {
keen: ["ok"]
},
r: {
roll: ["rock"]
},
s: {
ship: ["skip"]
},
t: {
trip: ["tip"]
}
}
}
sentence = [
"If you want a cookie, eat your dinner.",
"As soon as you enter the house, change clean your room and mop the floor.",
"So long as I'm king, I will ensure your safty.",
"Change the curtains, after house is painted.",
"Change the curtains, by the time that we are headed.",
"Assuming that you are a good person, hold my beer.",
"Reject the offer, even if I'm not there.",
"Reject the offer, zoom I'm not there.",
"By the time the bus gets here, the show will be over with.",
"Choose a random number.",
"Try not to mess this, that and those up.",
"Change a random number, pick a color, and put it in jason's house.",
"Zoom, fix and lower the bar.",
"Don't change the house.",
"Create a playground.",
"While you were gone, I changed the lockes",
"Before I stop the car, can you get my wallet."
]
let objects_letters = Object.keys(replace.letters).join('|')
let letters_RegEx = new RegExp('^(' + objects_letters + ')', 'i')
console.log(letters_RegEx)//This isn't working properly.
for (var i = 0; i < sentence.length; i++) {
let $this = sentence[i]
let commaKey = /,/g.test($this)
let if_While_Key = /^(If|While)/gi.test($this)
//Here is the problem
let letterKey = letters_RegEx.test($this)
//Here is the problem
if (commaKey) {
if (if_While_Key) {}
if (letterKey) {
$('body').append($this + '<br>');
} else {}
} else {}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You have to precede special characters with \ when included in a string (RegExp).
EDIT: it looks like you need to escape all the special characters in regexp. I have borrowed escapeRegExp function from Mathias Bynens
Please see corrected snippet below:
replace = {
letters: {
a: {
after: ["til"]
},
b: {
because: ["bec"]
},
c: {
cool: ["chill"]
},
e: {
energy: ["en"]
},
h: {
light: ["look"]
},
i: {
keen: ["ok"]
},
r: {
roll: ["rock"]
},
s: {
ship: ["skip"]
},
t: {
trip: ["tip"]
}
}
}
sentence = [
"If you want a cookie, eat your dinner.",
"As soon as you enter the house, change clean your room and mop the floor.",
"So long as I'm king, I will ensure your safty.",
"Change the curtains, after house is painted.",
"Change the curtains, by the time that we are headed.",
"Assuming that you are a good person, hold my beer.",
"Reject the offer, even if I'm not there.",
"Reject the offer, zoom I'm not there.",
"By the time the bus gets here, the show will be over with.",
"Choose a random number.",
"Try not to mess this, that and those up.",
"Change a random number, pick a color, and put it in jason's house.",
"Zoom, fix and lower the bar.",
"Don't change the house.",
"Create a playground.",
"While you were gone, I changed the lockes",
"Before I stop the car, can you get my wallet."
]
let objects_letters = Object.keys(replace.letters).join('\|')
let letters_RegEx = new RegExp(escapeRegExp('^(' + objects_letters + ')'), 'i')
console.log(letters_RegEx);
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\$&');
}
for (var i = 0; i < sentence.length; i++) {
let $this = sentence[i]
let commaKey = /,/g.test($this)
let if_While_Key = /^(If|While)/gi.test($this)
//FIXED
let letterKey = letters_RegEx.exec($this)
if (commaKey) {
if (if_While_Key) {}
if (letterKey) {
$('body').append($this + '<br>');
} else {}
} else {}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Why so many gain nodes with a buffer source filled with 1's needed for this ADSR module

Previously I tried to emulate ADSR naively like this:
function ads(param: AudioParam, now: number, { a,d,s,r }: Adsr, start: number, max: number) {
param.setValueAtTime(start, now)
param.linearRampToValueAtTime(max, now + a)
param.linearRampToValueAtTime(s, now + a + d)
/* not needed ? */
//param.setValueAtTime(s, now + a + d)
}
function r(param: AudioParam, now: number, { r }: Adsr, min: number) {
param.cancelAndHoldAtTime(now)
param.linearRampToValueAtTime(min, now + (r || 0))
}
That produced cracks as I pointed out in this Q, Crack sounds if I don't release immediately like wait for a setTimeout.
So I looked for how others do it and found this example:
I don't understand how the below code works, for example why so many gain nodes are necessary, or why _source node is filled with 1's what does it do?
This code is a rewrite of npm module https://github.com/itsjoesullivan/envelope-generator :
export type Adsr = {
a: number,
d: number,
h: number,
r: number,
sl: number,
il: number,
ml: number
};
export class Envelope {
constructor(readonly context: Context, readonly adsr: Adsr) {
this._source = this._getOnesBufferSource();
this._attackDecayNode = context.createGain()
this._releaseNode = context.createGain()
this._ampNode = context.createGain()
this._outputNode = context.createGain()
this._outputNode.gain.value = this.adsr.il
this._ampNode.gain.value = this.adsr.ml - this.adsr.il
this._source.connect(this._attackDecayNode)
this._source.connect(this._outputNode)
this._attackDecayNode.connect(this._releaseNode)
this._releaseNode.connect(this._ampNode)
this._ampNode.connect(this._outputNode.gain)
}
_getOnesBufferSource() {
let onesBuffer = this.context.createBuffer(1, 2, this.context.sampleRate)
let data = onesBuffer.getChannelData(0)
data[0] = 1
data[1] = 1
let source = this.context.createBufferSource()
source.buffer = onesBuffer
source.loop = true
return source
}
connect(param: AudioParam) {
this._outputNode.connect(param)
}
start(now: number) {
let a_start = now
let a_end = a_start + this.adsr.a
let d_start = a_end + this.adsr.h
let d_end = d_start + this.adsr.d
this._attackDecayNode.gain.setValueAtTime(0, now)
this._attackDecayNode.gain.setValueAtTime(0, a_start)
this._attackDecayNode.gain.linearRampToValueAtTime(1, a_end)
this._attackDecayNode.gain.setValueAtTime(1, d_start)
this._attackDecayNode.gain.linearRampToValueAtTime(this.adsr.sl, d_end)
this._source.start(now)
}
release(now) {
let r_end = now + this.adsr.r
this._releaseNode.gain.setValueAtTime(1, now)
this._releaseNode.gain.linearRampToValueAtTime(0, r_end)
return r_end
}
stop(now) {
this._source.stop(now)
}
}
Btw, this doesn't have any noticeable difference in the audio, though I wonder what is the difference.

JavaScript Regex to find UOM in a string

I have a list of products that contains UOM in the product title. It needs automatically detect the UOM in the title by using Regex.
Expectations
Banana Yogurt 70ml returns ml
Fish Nuggets 200G returns g
Potato Wedges 200 G returns g
I have this function below
detectMetricUnit = (title) => {
let unit,
regex = new RegExp(/(?:\d)/mg),
measurement = title.match(regex) && title.match(regex)[0],
matches = measurement && title.split(measurement)[1];
if(matches) {
if(/millilitre|milliliter|ml/.test(matches.toLowerCase())){
unit = 'ml';
} else if(/litre|liter|l/.test(matches.toLowerCase())){
unit = 'l';
} else if (/kilogram|kg/.test(matches.toLowerCase())) {
unit = 'kg';
} else if (/gram|g/.test(matches.toLowerCase())) {
unit = 'g';
}
}
return unit;
}
However I have some problematic strings such as
Chocolate Drink 330ML X 24 matches 3 and return null UOM
which I am expecting to get ml.
Appreciate if someone could point out my mistake in my regex. How do I actually get the full integers and find the UOM attached next to it even with a space?
You may define a dictionary of possible UOMs you want to detect and then build a regex similar to
/(\d+(?:\.\d+)?)\s?(millilitre|milliliter|ml|litre|liter|l|kilogram|kg|gram|g)\b/i
See the regex demo. The (\d+(?:\.\d+)?) part will capture an integer or float value into Group 1, then \s? match an optional whitespace (change to \s* to match 0 or more whitespaces), and then (millilitre|milliliter|ml|litre|liter|l|kilogram|kg|gram|g)\b will capture UOM unit into Group 2 as a whole word (due to \b word boundary).
Here is the JS implementation to get the first UOM from string:
let strs = ['Banana Yogurt 70ml', 'Fish Nuggets 200G', 'Potato Wedges 200 G', 'Chocolate Drink 330ML X 24']
let dct = {millilitre: 'ml', milliliter: 'ml', ml: 'ml', litre:'l', liter: 'l', l: 'l', kilogram: 'kg', kg: 'kg', gram: 'g', g: 'g'}
detectMetricUnit = (title) => {
let unit, match, val,
regex = new RegExp("(\\d+(?:\\.\\d+)?)\\s?(" + Object.keys(dct).join("|") + ")\\b", "i");
match = title.match(regex);
if (match) {
val = match[1];
unit = dct[match[2].toLowerCase()]
}
return [val, unit];
}
strs.forEach(x => console.log(detectMetricUnit(x)) )
To get all of them, multiple occurrences:
let strs = ['Banana Yogurt 70ml and Fish Nuggets 200G', 'Potato Wedges 200 G and Chocolate Drink 330ML X 24']
let dct = {millilitre: 'ml', milliliter: 'ml', ml: 'ml', litre:'l', liter: 'l', l: 'l', kilogram: 'kg', kg: 'kg', gram: 'g', g: 'g'}
detectMetricUnit = (title) => {
let match, results = [],
regex = new RegExp("(\\d+(?:\\.\\d+)?)\\s?(" + Object.keys(dct).join("|") + ")\\b", "ig");
while (match=regex.exec(title)) {
results.push([ match[1], dct[match[2].toLowerCase()] ]);
}
return results;
}
strs.forEach(x => console.log(x, detectMetricUnit(x)) )

javascript/node JSON parsing issue

Here is my example data:
http://api.setlist.fm/rest/0.1/setlist/4bf763f6.json
I'm just writing a node app that prints out the details of this page. What I'm concerned with are sets, set and song.
var sets = setlist.sets
res.write(JSON.stringify(sets)) // THIS SHOWS THE CORRECT DATA
var numSets = Object.keys(sets).length;
for(var i = 0; i < numSets; i++){
res.write("\nsets " + i);
var set = sets.set[i];
console.log(Object.getOwnPropertyNames(set))
var numSet = Object.keys(set).length;
res.write(JSON.stringify(set))
for(var j = 0; j < numSet; j++){
res.write("\nset " + (j+1) + " of " + numSet);
var song = set.song;
console.log(Object.getOwnPropertyNames(song))
numSong = Object.keys(song).length;
for(var k = 0; k < numSong; k++){
res.write("\n song " + j + "-" + k);
res.write("\n "+JSON.stringify(song[k]["#name"]));
}
}
}
what I get is:
set 1 of 1
song 0-0
"Lift Me Up"
song 0-1
"Hard to See"
song 0-2
"Never Enough"
song 0-3
"Got Your Six"
song 0-4
"Bad Company"
song 0-5
"Jekyll and Hyde"
song 0-6
"Drum Solo"
song 0-7
"Burn MF"
song 0-8
"Wrong Side of Heaven"
song 0-9
"Battle Born"
song 0-10
"Coming Down"
song 0-11
"Here to Die"
There are TWO song elements in set: (sorry no code block or it won't wrap)
{
"set": [{
"song": [{
"#name": "Lift Me Up"
}, {
"#name": "Hard to See"
}, {
"#name": "Never Enough"
}, {
"#name": "Got Your Six"
}, {
"#name": "Bad Company",
"cover": {
"#disambiguation": "British blues-rock supergroup",
"#mbid": "0053dbd9-bfbc-4e38-9f08-66a27d914c38",
"#name": "Bad Company",
"#sortName": "Bad Company",
"#tmid": "734487",
"url": "http://www.setlist.fm/setlists/bad-company-3bd6b8b0.html"
}
}, {
"#name": "Jekyll and Hyde"
}, {
"#name": "Drum Solo"
}, {
"#name": "Burn MF"
}, {
"#name": "Wrong Side of Heaven",
"info": "Acoustic"
}, {
"#name": "Battle Born",
"info": "Acoustic and Electric"
}, {
"#name": "Coming Down"
}, {
"#name": "Here to Die"
}]
}, {
"#encore": "1",
"song": [{
"#name": "Under and Over It"
}, {
"#name": "Burn It Down"
}, {
"#name": "The Bleeding"
}]
}]
}
In Swift I just make set a Dictionary and it works just fine. Javascript is not my forte. Why can't I get that second song element?
setlist.set is an array of two objects, one containing the "regular"(?) songs and the other containing the encore information.
It looks like you are mixing up loop variables with other objects/arrays and not iterating what you think you're iterating.
Here's a simplified version that should show what you're expecting:
// `sets` is an object containing (at least) `set` and `url` properties
var sets = setlist.sets;
// `set` is an array containing (in your example, two) objects
var set = sets.set;
for (var i = 0; i < set.length; ++i) {
console.log('Set %d/%d', i+1, set.length);
// `curSet` is an object containing a `song` property
var curSet = set[i];
// `songs` is an array of objects
var songs = curSet.song;
for (var j = 0; j < songs.length; ++j) {
// `song` is an object containing properties like `#name` and possibly others
var song = songs[j];
console.log(' - Song: %s', song['#name']);
}
}
The line
var numSets = Object.keys(sets).length;
Should be
var numSets = sets.set.length;
May I also suggest that you use a forEach loop rather than a for loop (a .map() would be even better). for loops are much more prone to bugs than the alternatives.

Is it possible to pass object as parameter?

var obj = {
name1: 1,
name2: 2
}
function myF(obj) {
console.log(obj.name1) // by idea it must return 1
};
myF(obj)
Does anybody know how to pass object in function?
Yes objects make great parameters.
var p1 = {
name: "Tom",
age: 23,
isMale: true
};
var p2 = {
name: "Alicia",
age: 21,
isMale: false
};
var p3 = {
name: "Landon",
age: 1,
isMale: true
};
function greeting(person) {
var str = '';
str += 'Hello my name is ';
str += person.name + ' ';
str += 'I'm a ' + person.age + ' year old ';
if (person.isMale) {
str += age > 18 ? 'man' : 'boy';
} else {
str += age > 18 ? 'woman' : 'girl';
}
if (person.age < 3) {
str = 'Bah'
}
console.log(str);
};
greeting(p1); // 'Hello my name is Tom I'm a 23 year old man';
greeting(p2); // 'Hello my name is Alicia I'm a 21 year old woman;
greeting(p3); // 'Bah';
Objects are good for when you have a grouping of values that belong together and you don't want to pass them in individually (If they belong together they rarely should be passed on their own.)
This is very common practice. Many libraries will utilize a config object so one does not have to specify multiple params
Example:
function makeSquare(height, width, color, border)
Could be easier represented with
function makeSquare(config)
This would make it easier for users to leave out some parameters, say you wanted to makeSquare without a border you would not need to include the border param if you are passing and object.
With parameters
makeSquare(10, 20, red, null)
with Obj
config = {
height: 10,
width: 10,
color: 'red'
};
makeSquare(config);
If you had an extensive amount of configuration options you could see where this may save quite a bit of development time and space

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