I need help with this between function. My clock here is 24 hours.
I always get the "else" option. What is wrong with the code?
// Get time
var today = new Date();
var time = today.getHours();
console.log(time); // 8 o clock right now when I am testing
// Between function
Number.prototype.between = function(first, last) {
return first < last ? this >= first && this <= last : this >= last && this <= first;
};
// Do something
if (time.between(7, 9)) {
console.log("between(7, 9)",time.between(7, 9))
}
if (time.between(9, 15)) {
console.log("between(9, 15)",time.between(9, 15))
}
if (time.between(15, 18)) {
console.log("between(15, 18)",time.between(15, 18))
}
// and so on
else {
console.log("else")
}
The else only connects the last if. Just write else ifs
// Get time
var today = new Date();
var time = today.getHours();
console.log(time); // 8 o clock right now when I am testing
// Between function
Number.prototype.between = function(first, last) {
return first < last ? this >= first && this <= last : this >= last && this <= first;
};
// Do something
if (time.between(7, 9)) {
console.log("between(7, 9)",time.between(7, 9))
}
else if (time.between(9, 15)) {
console.log("between(9, 15)",time.between(9, 15))
}
else if (time.between(15, 18)) {
console.log("between(15, 18)",time.between(15, 18))
}
// and so on
else {
console.log("else")
}
Related
Just playing around with functions..
The live server shows undefined.
However; when I just run the javascript code-the correct greetings show.
Why is this?
What can I do to fix it?
const today = new Date();
let now = today.getHours(); //0-23
let time;
/*morning: 0300 - 1100
*morning >= 0300 && morning < 11
*afternoon 1100-1900
*afternoon >= 11 && afternoon < 19
*evening 1900 - 0300
*evening >= 19 && evening < 3
*/
if (now >= 5 && now < 11) {
time = 'morning';
} else if (now >= 11 && now < 17) {
time = 'afternoon';
} else if (now >= 17 && now < 23) {
time = 'night';
} else {
time = 'sleep';
}
//console.log(time);
function greeting() {
if (time === 'morning') {
console.log('Good Morning!');
console.log('I love you!');
console.log("You're doing GREAT!");
console.log('Nice butt!');
} else if (time ==='afternoon') {
console.log('Good afternoon!');
console.log("You're a genius!");
console.log('Just keep swimming!');
console.log('Progress not perfection!');
} else if (time === 'night') {
console.log('Goodnight, Princess!');
console.log('Time for a nightcap.');
console.log ('Sleep tight!');
console.log ('Get NAKED!');
} else {
console.log('GO TF\' TO SLEEP');
console.log('GO TF\' TO SLEEP');
console.log('GO TF\' TO SLEEP');
console.log('GO TF\' TO SLEEP');
}
}
//greeting();
document.write('<h1>' + greeting() + '</h1>');
??
console.log() prints to the console (F12 in normal browsers). You probably want to replace all console.log() with document.write('<yourTag>Message</yourTag>');.
Otherwise, if you want to use the output of the function the you can create an empty string variable and concat your messages and return them.
function functionName() {
let result = '';
result = result + 'my Test';
result = result + ' my Test 2';
return result;
}
Of course you can use structures control structures (if/else) with both ways.
greeting() method does not return anything that's why you are getting undefined
function greeting(){
return 'Say Hello!'
}
Now this will shows you
<h1>Say Hello!</h1>
I have a problem where the babysitter earns different rates depending on times:
The babysitter
- starts no earlier than 5:00PM
- leaves no later than 4:00AM
- gets paid $12/hour from start-time to bedtime
- gets paid $8/hour from bedtime to midnight
- gets paid $16/hour from midnight to end of job
- gets paid for full hours (no fractional hours)
I'm wondering why I'm getting undefined when I pass through times in this function?
function calculatePay (startTime, bedTime, endTime){
function formatTime(time){
if (time.indexOf('00') === -1){
time = Number(time.split(":").shift()) + 1;
} else {
time = Number(time.split(":").shift());
}
if (time < 5) {
time = time + 12;
}
return time;
};
var start = formatTime(startTime);
var bedtime = formatTime(bedTime);
var end = formatTime(endTime);
var scheduleRange = {
start: 5,
lateNight: 12,
end: 16,
}
var payrate = {
beforeBed: 12,
sleeping: 8,
afterMidnight: 16
}
var calculateBeforeBed = function (start, bedtime) {
if (bedtime > start && bedtime <= scheduleRange.lateNight){
var beforeBedEarned = (bedtime - start) * payrate.beforeBed;
return beforeBedEarned;
} else if (bedtime > scheduleRange.lateNight) {
var beforeBedEarned = (scheduleRange.lateNight - start) * payrate.beforeBed;
return beforeBedEarned;
} else {
return 0;
}
};
var calculateAfterBed = function (start, bedtime, end) {
if (bedtime > start && bedtime <= scheduleRange.lateNight && bedtime <= end) {
var afterBedEarned = (scheduleRange.lateNight - bedtime) * payrate.sleeping;
return afterBedEarned;
} else if (bedtime <= start && end <= scheduleRange.lateNight){
afterBedEarned = (end - start) * payrate.sleeping;
return afterBedEarned;
} else if (bedtime <= start && end > scheduleRange.lateNight){
afterBedEarned = (scheduleRange.lateNight - start) * payrate.sleeping;
return afterBedEarned;
}
else {
return 0;
}
};
var calculateAfterMidnight = function (start, end) {
if (end > scheduleRange.lateNight && start <= scheduleRange.lateNight) {
var lateNightEarned = (end - scheduleRange.lateNight) * payrate.afterMidnight;
return lateNightEarned;
} else if (end > scheduleRange.lateNight && start > scheduleRange.lateNight) {
lateNightEarned = (end - start) * payrate.afterMidnight;
return lateNightEarned;
} else {
return 0;
}
};
function finalInvoice (start, bedtime, end){
if(start >= scheduleRange.start && end <= scheduleRange.end){
var pay = calculateBeforeBed(start, bedtime) + calculateAfterBed(start, bedtime, end)+ calculateAfterMidnight(start, end);
return pay;
};
};
}
calculatePay("7:00", "10:00", "1:00");
because your function has no return statement
function voidsum(a, b, c) {
var result = a + b + c;
}
function sum(a, b, c) {
var result = a + b + c;
return result;
}
console.log('voidfn', voidsum(123, 321, 231));
console.log('sum', sum(123, 321, 231));
added a while loop, and trying to end the loop by entering finish inside the loop. The game is still running after it the game is completed.
var number = Math.floor(Math.random() * 100) + 1; // generate random #
var guess;
var guessCount = 0;
var correctGuess = false;
var diff;
var correct = false;
while (!correct) {
correct = guessFunction();
var finish = false;
}
function guessFunction(){
guess = prompt('I am thinking of a number between 1 and 100. What is it?');
guessCount += 1;
var guessInt = parseInt(guess); //turn guesses into interger
if (guess == number){ //which number is bigger, guess or number
alert('Correct!' + 'That was a total of ' + guessCount + ' guesses.');
correctGuess = true;
finish = true;
}
else if (guessInt > number) {
diff = guessInt - number;
}
else if (guessInt < number) {
diff = number - guessInt;
}
if (diff >= 1 && diff <= 10 && !correctGuess) {
alert('Very Hot');
guessFunction();
}
else if (diff < 10 && diff <= 20 && !correctGuess){
alert('Hot');
guessFunction();
}
else if (diff < 20 && diff <= 30 && !correctGuess){
alert('Warm');
guessFunction();
}
else if (diff < 30 && diff <= 50 && !correctGuess){
alert('Cold');
guessFunction();
}
else if (diff > 50 && !correctGuess){
alert('Ice Cold');
guessFunction();
}
}
guessFunction();
Trying to get this code to run but it only allows for 2 alert windows when guessing the random number. Im not sure how to get this to run, perhaps the guessFunction is not running?
var number = Math.floor(Math.random() * 100) + 1; // generate random #
var guess;
var guessCount = 0;
var correctGuess = false;
var diff;
function guessFunction(){
guess = prompt('I am thinking of a number between 1 and 100. What is it?');
guessCount += 1;
var guessInt = parseInt(guess); //turn guesses into interger
if (guess == number){ //which number is bigger, guess or number
alert('Correct!');
}
else if (guessInt > number) {
diff = guessInt - number;
}
else if (guessInt < number) {
diff = number - guessInt;
}
}
guessFunction();
if (diff >= 1 && diff <= 10) {
alert('Very Hot');
guessFunction();
}
else if (diff < 10 && diff <= 20){
alert('Hot');
guessFunction();
}
else if (diff < 20 && diff <= 30){
alert('Warm');
guessFunction();
}
else if (diff < 30 && diff <= 50){
alert('Cold');
guessFunction();
}
else if ( diff > 50){
alert('Ice Cold');
guessFunction();
}
The script stops executing because you only call your function twice. If you want this to run until the user guesses the right number, you probably want a while loop:
var correct = false;
while (!correct) {
// guessFunction could return true if they get it right
correct = guessFunction();
}
Yes, your script is only executing twice before exiting. You've got your nesting wrong:
var number = Math.floor(Math.random() * 100) + 1; // generate random #
var guess;
var guessCount = 0;
var correctGuess = false;
var diff;
function guessFunction(){
guess = prompt('I am thinking of a number between 1 and 100. What is it?');
guessCount += 1;
var guessInt = parseInt(guess); //turn guesses into interger
if (guess == number){ //which number is bigger, guess or number
alert('Correct!');
correctGuess = true;
}
else if (guessInt > number) {
diff = guessInt - number;
}
else if (guessInt < number) {
diff = number - guessInt;
}
if (diff >= 1 && diff <= 10 && !correctGuess) {
alert('Very Hot');
guessFunction();
}
else if (diff < 10 && diff <= 20 && !correctGuess){
alert('Hot');
guessFunction();
}
else if (diff < 20 && diff <= 30 && !correctGuess){
alert('Warm');
guessFunction();
}
else if (diff < 30 && diff <= 50 && !correctGuess){
alert('Cold');
guessFunction();
}
else if (diff > 50 && !correctGuess){
alert('Ice Cold');
guessFunction();
}
}
guessFunction();
EDIT:
My answer is more verbose than it needs to be so that it relates directly to your question. The next step for you is to implement the better solution of a while loop mentioned in Menello's answer in your script.
User input time in the decimal format.
like
0.00 //Incorrect
1.54 //Correct value
1.60 //Incorrect value
1.59 //correct value
I have tried to make a regular expression function but it is showing incorrect for all values
var regex = /^[0-9]\d*(((,?:[1-5]\d{3}){1})?(\.?:[0-9]\d{0,2})?)$/;
if (args.Value != null || args.Value != "") {
if (regex.test(args.Value)) {
//Input is valid, check the number of decimal places
var twoDecimalPlaces = /\.\?:[1-5]\d{2}$/g;
var oneDecimalPlace = /\.\?:[0-9]\d{1}$/g;
var noDecimalPlacesWithDecimal = /\.\d{0}$/g;
if (args.Value.match(twoDecimalPlaces)) {
//all good, return as is
args.IsValid = true;
return;
}
if (args.Value.match(noDecimalPlacesWithDecimal)) {
//add two decimal places
args.Value = args.Value + '00';
args.IsValid = true;
return;
}
if (args.Value.match(oneDecimalPlace)) {
//ad one decimal place
args.Value = args.Value + '0';
args.IsValid = true;
return;
}
//else there is no decimal places and no decimal
args.Value = args.Value + ".00";
args.IsValid = true;
return;
} else
args.IsValid = false;
} else
args.IsValid = false;
It's probably easier to do working with a number:
var time = (+args.Value).toFixed(2); // convert to float with 2 decimal places
if (time === args.Value) {
// it's a valid number format
if (time !== 0.0 && time < 24) {
// the hours are valid
if (time % 1 < 0.6) {
// the minutes are valid
}
}
}
You can collapse all that up into a nice one-liner:
if (time === args.Value && time !== 0.0 && time < 24 && time % 1 < 0.6) {
}
and even a boolean/ternary
var valid = time === args.Value && time !== 0.0 && time < 24 && time % 1 < 0.6;
alert( time === args.Value && time !== 0.0 && time < 24 && time % 1 < 0.6 ? 'valid' : 'invalid' );
Assume i have a function checkTime like the one below where i have to check for multiple condition simultaneously.
var result=0;
function checkTime(time1, time2) {
if (time1 >= 0 && time2 <= 0) {
result = 1;
}
else if (time1 >= 0 && time2 <= 1) {
result = 4;
}
else if (time1 >= 2 && time2 <= 3) {
result = 5;
}
else if (time1 >= 4 && time2 <= 6) {
result = 6;
}
else if (time1 >= 7 && time2 <= 9) {
result = 7;
}
else if (time1 >= 11 && time2 <= 12) {
result = 8;
}
else if (time1 >= 13 && time2 <= 15) {
result = 9;
}
else if (time1 >= 16 && time2 <= 17) {
result = 10;
}
else if (time1 >= 19 && time2 <= 20) {
result = 11;
}
return result;
}
(The above given example is hypothetical)
The function i have used totally works,but:
Is there a better method or procedure or formula to replace this?(where it doesnt have to be this lengthy or ugly)
Thanx!
You can use an array to represent all the combination:
tests = [
{ time1: 0, time2: 0, result: 1 },
{ time1: 0: time2: 1, result: 4 },
...
];
for (var i = 0; i < tests.length; i++) {
if (time1 >= tests[i].time1 && time2 <= tests[i].time2) {
return tests[i].result;
}
}
If the code is identical, and only the values change, you could do something like this:
function checkTime(time1, time2) {
[
[0, 0, 0],
[0, 1, 0]
].forEach(function (it) {
if (time1 >= it[0] && time2 <= it[1]) {
return it[2];
}
});
}
Well, first off you have the possibility of an undefined result, so that makes things ambiguous. Should result start at 0 instead? This is an important detail. Second, you seem to be working with boundaries, so it would help to change the <= to < to make this clearer. (If so, the 7-9/11-12 section has a bug.) Third, you have an implicit comparison of time1 and time2, so make that explicit.
var result = 0;
var diff = time2 - time1;
var bounds = [21, 19, 16, 13, 11, 7, 4, 2, 0];
if (diff <= 0) result = 0; // unexpected outcome
else
for (position = 1; position < bounds.length; ++position) {
if (time1 >= bounds[position]) {
if (time2 < bounds[position - 1]) {
result = 3 + (bounds.size - position);
}
break;
}
}
return result;
Other implementations are possible, but it's hard to tell based on your question exactly what problem you're solving.
follow-up
This section of code has a gap:
else if (time1 >= 7 && time2 <= 9) {
result = 7;
}
else if (time1 >= 11 && time2 <= 12) {
result = 8;
}
If time = 10 and time2 = 10, there is no match. It's easy to miss this type of error when you are repeating yourself. Specifying lower and upper bounds for each condition is unnecessary repetition. Since I couldn't see a pattern to the bounds (which could be delegated to a function), I just put the lower bounds into an array and made sure it was sorted descending so that the loop could stop after the first match.