Javascript IF/ELSE - Shorten function - javascript

I am playing around with the JavaScript IF/ELSE to understand better how it works. As an exercise I took the following working hours of a shop:
6AM to 6PM = Open
6PM to 6AM = Closed
then I created a function that returns the word 'Open' or 'Closed' based on the 2 values "time" and "period".
function shopHours(time,period) {
if (time === 6 && period === 'AM') {
return 'Open';
} else if (time === 6 && period === 'AM') {
return 'Open';
} else if (time === 7 && period === 'AM') {
return 'Open';
} else if (time === 8 && period === 'AM') {
return 'Open';
} else if (time === 9 && period === 'AM') {
return 'Open';
} else if (time === 10 && period === 'AM') {
return 'Open';
} else if (time === 11 && period === 'AM') {
return 'Open';
} else if (time === 12 && period === 'PM') {
return 'Open';
} else if (time === 1 && period === 'PM') {
return 'Open';
} else if (time === 2 && period === 'PM') {
return 'Open';
} else if (time === 3 && period === 'PM') {
return 'Open';
} else if (time === 4 && period === 'PM') {
return 'Open';
} else if (time === 5 && period === 'PM') {
return 'Open';
} else {
return 'Closed';}
}
Everything works fine. However, I would like to be able to shorten the code as it looks too confusing.
I then tried the following:
function shopHours(time,period) {
if(time <= 6 && period === 'AM') {
return 'Closed';
} else if (time >= 6 && period === 'PM') {
return 'Closed';
} else if (time === 12 && period === 'PM') {
return 'Open';
} else {
return 'Open';}
}
The second code works fine too and is much shorter however there is a problem that I am not sure how to solve. When the time and period are set to 12 and PM, the result should be 'closed' but I am not sure how to implement this.
I have tried to add the following code but it seems that would not solve this problem.
else if (time === 12 && period === 'AM') {
return 'Closed';
}
I will be very grateful to anyone that will spend a bit of his time to take a look at this question.
Thank you!

You can break it down into two initial scenarios, either AM or PM. Then check the hour to see if it should be open or closed.
if (period == "AM") {
if (time < 6 || time == 12)
return "Closed";
return "Open";
}
else {
if (time >= 6 && time != 12)
return "Closed";
return "Open";
}

It's easier to work with 24-hour format, in my opinion.
One has to take 12PM = 12:00 and 12AM = 00:00 into account however.
After conversion the comparision is fairly easy.
function shopHours(time, period) {
let hour = time;
if (period === 'PM' && hour < 12) hour = hour + 12;
if (period === 'AM' && hour === 12) hour = hour - 12;
if (hour >= 6 && hour < 18) {
return 'Open';
}
return 'Closed';
}
console.log('12 AM is ' + shopHours(12, 'AM') + '. Expected it to be: Closed');
console.log('3 AM is ' + shopHours(3, 'AM') + '. Expected it to be: Closed');
console.log('6 AM is ' + shopHours(6, 'AM') + '. Expected it to be: Open');
console.log('9 AM is ' + shopHours(9, 'AM') + '. Expected it to be: Open');
console.log('12 PM is ' + shopHours(12, 'PM') + '. Expected it to be: Open');
console.log('3 PM is ' + shopHours(3, 'PM') + '. Expected it to be: Open');
console.log('6 PM is ' + shopHours(6, 'PM') + '. Expected it to be: Closed');
console.log('9 PM is ' + shopHours(9, 'PM') + '. Expected it to be: Closed');

My version.if goal is to just shorten the code, then those am() and pm() functions can be omitted and the code inside can be added where am calling them. That would be 3 lines of code.
function shopHours(time, period){
var result;
function am () {
Number(time) < 12 && Number(time) >= 6 ? result = "open" : result = "closed";
}
function pm() {
Number(time) <= 5 || Number(time) === 12 ? result = "open" : result = "closed";
}
period === 'AM' ? am() : pm();
return result;
}
console.log("12 AM is: ", shopHours(12, 'AM'), '; expected: closed');
console.log("3 AM is: ", shopHours(3, 'AM'), '; expected: closed');
console.log("6 AM is: ", shopHours(6, 'AM'), '; expected: open');
console.log("9 AM is: ", shopHours(9, 'AM'), '; expected: open');
console.log("12 PM is: ", shopHours(12, 'PM'), '; expected: open');
console.log("3 PM is: ", shopHours(3, 'PM'), '; expected: open');
console.log("6 PM is: ", shopHours(6, 'PM'), '; expected: closed');
console.log("9 PM is: ", shopHours(9, 'PM'), '; expected: closed');

This can be easily handled using date instead. Instead of using if else, You can define the openHours and closeHours. And pass the current time. You can easily compare then.
Sample:
function shopHours(time, period) {
let openHour = new Date();
let closeHour = new Date();
openHour.setHours(6);
closeHour.setHours(12 + 6);
let curreTime = new Date();
curreTime.setHours(period === "PM" ? 12 + time : time);
if (curreTime > openHour && curreTime < closeHour) return "Open";
return "Close";
}
console.log(shopHours(11, "PM"));
console.log(shopHours(12, "AM"));
console.log(shopHours(11, "AM"));
console.log(shopHours(7, "AM"));
console.log(shopHours(5, "AM"));
You can also just pass the currentTime and validate.
function shopHours(curreTime) {
let openHour = new Date();
let closeHour = new Date();
openHour.setHours(6);
closeHour.setHours(12 + 6);
if (curreTime > openHour && curreTime < closeHour) return "Open";
return "Close";
}
console.log(shopHours(new Date()));

My suggestion:
function shopHours(time, period) {
var status = "Open";
if ((period == "AM" && (time < 6 || time == 12)) || (time >= 6 && time != 12)) status = "Closed";
return status;
}
console.log(shopHours(5, "AM"));
console.log(shopHours(5, "PM"));

Related

JS template literals: not defined

As I'm writing this function which holds a parameter 'day', I'de like to log the chosen day to the console.
I'm getting the output 'day is not defined' and I cannot figure out why (I'm new to JS).
I believe 'day' is defined because I call the function with an argument.
const getSleepHours = day => {
if (day === 'monday'){
return 8;
} else if (day === 'tuesday'){
return 7;
} else if (day === 'wednesday'){
return 8;
} else if (day === 'thursday'){
return 9;
} else if (day === 'friday'){
return 8;
} else if (day === 'saturday'){
return 9;
} else if (day === 'sunday'){
return 9;
} else {
return 'Please enter a valid day';
}
};
console.log('You have slept for: ' + getSleepHours('sunday') + ' hours');
console.log(`${day}`);
In the function definition syntax, "day" has to be wrapped in paranthesis () as (day). Below is how i would implement it
const getSleepHours = (day) => {
var hours = 0;
switch(day){
case "sunday":
hours=1;
break;
case "monday":
hours=2;
break;
default:
hours=0;
}
return hours;
}
const daysCount = getSleepHours('sunday');
console.log('You have slept for: '+ getSleepHours("sunday") +' hours');
console.log(daysCount);
const getSleepHours = day => { // this day variable will be considered as argument
if (day === 'monday'){
return 8;
} else if (day === 'tuesday'){
return 7;
} else if (day === 'wednesday'){
return 8;
} else if (day === 'thursday'){
return 9;
} else if (day === 'friday'){
return 8;
} else if (day === 'saturday'){
return 9;
} else if (day === 'sunday'){
return 9;
} else {
return 'Please enter a valid day';
}
};
const day = getSleepHours('sunday'); // define day variable so value will be stored which is returned from function.
console.log('You have slept for: ' + getSleepHours('sunday') + ' hours');
console.log(`${day}`);

JavaScript - Console.log return something but with return it shows undefined

the problem as the title said : The console.log show the correct value but when I return it and show it with the DOM by adding a paragraph (using jQuery) in the paragraph it shows undefined...
console.log(dateTimeUTC(timeZoneStr));
// Shows the correct value I wanted
return dateTimeUTC(timeZoneStr);
// Shows undefined
So what I want to do : A form with html with a simple input text and a submit button, when the submit button is click so it saves the text of the input in a variable using jQuery : let variable = $('#cityName').val(); (the value should be a city name) because when I've got the city name value I ask the openweathermap API to send me the json and to give the value of the timezone in ms then I need to convert the ms value in hour so for example New York, : timezone: -14400 (json.timezone / 60 / 60) so the result with New york is UTC - 4, then I have a script that convert my UTC thing in an real date time but that script work so I don't need to explain you... when that function finish it gives me the result like that :
Tue Aug 13 2019 05:53:39 GMT+0200
Not really good for presentation so then I made a function that convert this in a better way :
year = timeNow.getFullYear();
month = ('0'+(timeNow.getMonth()+1)).slice(-2);
day = ('0'+timeNow.getDate()).slice(-2);
hour = ('0'+timeNow.getHours()).slice(-2);
minute = ('0'+timeNow.getMinutes()).slice(-2);
second = ('0'+timeNow.getSeconds()).slice(-2);
showDateTimeValue = day + "/" + month + "/" + year + " - " + hour + ":" + minute + ":" + second;
return showDateTimeValue;
Then this return value go where I executed the function so in the function called timeZone and it's there that I've got the console.log working but with return it shows undefined.
Hopefully, I explained well and you'll understand what I'm trying to do, if anyone can give me some help ^_^
EDIT - FULL CODE :
Index.html code :
<div class="form-group">
<label for="cityName">Displays the local date and time according to the name of the city</label>
<input name="cityName" type="text" id="cityName" placeholder="Enter a name of a city..." class="form-control">
</div>
<br>
<button type="submit" id="submit">Submit</button>
<p class="results"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="./scripts/main.js"></script>
main.js code :
$(function () {
$( "#submit" ).click(function() {
let city = $('#cityName').val();
cityName = city.split(' ').join('+');
if(cityName === "") {
$('.results').append("<p>Wrong location.</p>");
}
else {
$('.results').append("<p>The date and time of " + city + " : " + weatherRequest("http://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&units=metric&appid=MyAPIkey") +'</p>');
}
});
})
Function code :
/* Function variable */
const messageError = "You didn't enter a valid thing.";
let timeNow = new Date();
let utcOffset = timeNow.getTimezoneOffset();
timeNow.setMinutes(timeNow.getMinutes() + utcOffset);
// Function that gives the date and hour utc time
function dateTimeUTC(utc) {
if(typeof utc === 'string' && utc.length >= 1 && utc[0] === '-' || '0' || '+' || !isNaN(parseFloat(utc[0])))
{
if (utc[0] === '0' && utc.length === 1)
{
let enteredOffset = 0;
return showDateTime(enteredOffset);
}
else if (utc[0] === '+' || !isNaN(parseFloat(utc[0])))
{
if (utc.length === 2 && utc[0] === '+')
{
// Entered offset
let enteredOffset = parseFloat(utc[1])*60;
timeNow.setMinutes(timeNow.getMinutes() + enteredOffset);
return showDateTime(enteredOffset);
}
else if (utc.length === 3 && utc[0] === '+')
{
// Entered offset
let enteredOffset = parseFloat(utc[1] + utc[2])*60;
timeNow.setMinutes(timeNow.getMinutes() + enteredOffset);
return showDateTime(enteredOffset);
}
else if (utc.length === 1 && !isNaN(parseFloat(utc[0])))
{
// Entered offset
let enteredOffset = parseFloat(utc[0])*60;
timeNow.setMinutes(timeNow.getMinutes() + enteredOffset);
return showDateTime(enteredOffset);
}
else if (utc.length === 2 && !isNaN(parseFloat(utc[0])))
{
// Entered offset
let enteredOffset = parseFloat(utc[0] + utc[1])*60;
timeNow.setMinutes(timeNow.getMinutes() + enteredOffset);
return showDateTime(enteredOffset);
}
else
{
let enteredOffset = 0;
return showDateTime(enteredOffset);
}
}
else if (utc[0] === '-')
{
if (utc.length === 2 && utc[0] === '-')
{
// Entered offset
let enteredOffset = - parseFloat(utc[1])*60;
timeNow.setMinutes(timeNow.getMinutes() + enteredOffset);
return showDateTime(enteredOffset);
}
else if (utc.length === 3 && utc[0] === '-')
{
// Entered offset
let enteredOffset = - parseFloat(utc[1] + utc[2])*60;
timeNow.setMinutes(timeNow.getMinutes() + enteredOffset);
return showDateTime(enteredOffset);
}
else
{
let enteredOffset = 0;
return showDateTime(enteredOffset);
}
}
else
{
let enteredOffset = 0;
return showDateTime(enteredOffset);
}
}
else if (utc === '' || !utc || utc === undefined)
{
utc = false;
let enteredOffset = 0;
return showDateTime(enteredOffset);
}
else
{
let enteredOffset = 0;
return showDateTime(enteredOffset);
}
}
// Function that shows the date and time correctly (format : dd/mm/yyyy - 00:00:00)
function showDateTime(enteredOffset) {
year = timeNow.getFullYear();
month = ('0'+(timeNow.getMonth()+1)).slice(-2);
day = ('0'+timeNow.getDate()).slice(-2);
hour = ('0'+timeNow.getHours()).slice(-2);
minute = ('0'+timeNow.getMinutes()).slice(-2);
second = ('0'+timeNow.getSeconds()).slice(-2);
showDateTimeValue = day + "/" + month + "/" + year + " - " + hour + ":" + minute + ":" + second;
timeNow.setMinutes(timeNow.getMinutes() - enteredOffset)
return showDateTimeValue;
}
// Function which get the shift in seconds between the utc with the API
function timeZone(json) {
let timeZone = json.timezone / 60 / 60;
let timeZoneStr = timeZone.toString();
// console.log("La date et l'heure de " + cityName.split('+').join(' ') + " : " + dateTimeUTC(timeZoneStr));
console.log(dateTimeUTC(timeZoneStr)); // Shows the correct value I wanted
return dateTimeUTC(timeZoneStr); // Shows undefined
}
// Function that request the openweathermap.org API
function weatherRequest(url) {
// console.log(url);
try
{
$.getJSON(url, function(json) {
timeZone(json);
});
}
catch
{
console.log("Wrong location.");
}
}
Alright somebody help me to find out why it was wrong so here is the solution :
Since we can't know when a request ended or such, you can't return value outside the getJSON, you need to append the things you want directly in the getJSON thingy so yeah here is the code in main.js :
$( "#submit" ).click(function()
{
let city = $('#cityName').val();
let cityName = city.split(' ').join('+');
if(cityName === "")
{
$('.results').append("<p>Wrong location.</p>");
}
else
{
weatherRequest("http://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&units=metric&appid=MyAPIkey");
}
});
Only need to change the function weatherRequest :
function weatherRequest(url) {
// console.log(url);
try
{
$.getJSON(url, function callbackSuccess(json) {
let showDateTimeValue = timeZone(json);
let city = json.name;
$('.results').append("<p>The date and time of " + city + " : " + showDateTimeValue + '</p>');
});
}
catch
{
$('.results').append("<p>Wrong location.</p>");
}
}
Hopefully you understood, i'm bad for explaining so yeah...

`if (Date >= Date1 && <= Date2 ){do this}` dosnĀ“t work

The code changes the new Date() to DayHourMinute
e.g. monday9AM45minutes to 010945
What I use is 010945 and my code specifies
if the var is between >=010921 && <=011010
change the background to green else nothing
But nothing happens and if I use alert(Time) it gives the message 010945.
How can if fix this?
Code:
function one() {
now = new Date();
hour = "" + now.getHours();
if (hour.length == 1) {
hour = "0" + hour;
}
minute = "" + now.getMinutes();
if (minute.length == 1) {
minute = "0" + minute;
}
day = "" + now.getDay();
if (day.length == 1) {
day = "0" + day;
}
var Time = day + '' + hour + '' + minute;
if (Time >= 010835 && Time <= 010920) {
document.getElementById('Man1').style.background = 'green';
} else {
document.getElementById('Man1').style.background = '';
}
if (Time >= 010921 && Time <= 011010) {
document.getElementById('Man2').style.background = 'green';
} else {
document.getElementById('Man2').style.background = '';
}
if (Time >= 011011 && Time <= 011105) {
document.getElementById('Man3').style.background = 'green';
} else {
document.getElementById('Man3').style.background = '';
}
if (Time >= 011106 && Time <= 011155) {
document.getElementById('Man4').style.background = 'green';
} else {
document.getElementById('Man4').style.background = '';
}
if (Time >= 011156 && Time <= 011239) {
document.getElementById('Man5').style.background = 'green';
} else {
document.getElementById('Man5').style.background = '';
}
if (Time >= 011240 && Time <= 011325) {
document.getElementById('Man6').style.background = 'green';
} else {
document.getElementById('Man6').style.background = '';
}
if (Time >= 011326 && Time <= 011415) {
document.getElementById('Man7').style.background = 'green';
} else {
document.getElementById('Man7').style.background = '';
}
if (Time >= 011416 && Time <= 011505) {
document.getElementById('Man8').style.background = 'green';
} else {
document.getElementById('Man8').style.background = '';
}
if (Time >= 011506 && Time <= 011555) {
document.getElementById('Man9').style.background = 'green';
} else {
document.getElementById('Man9').style.background = '';
}
}
setInterval(one, 1000);
Fiddle
Time is a string, and you are comparing to an int. Put the values in quotes:
if ( Time>='020000' && Time<='030000' ){

JavaScript does not take an account of the conditions exit, while variables are nevertheless equal to the output condition

I have a HTML form that submit to a JavaScript, the data is processed and a POST request is sent to a PHP script.
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
if(contentElt && xmlHttp.responseText) {
var ajaxData = JSON.parse(xmlHttp.responseText);
var processedResultCount = parseInt(ajaxData[0]);
totalResultCount += processedResultCount;
contentElt.innerHTML = "Date processed (month - year): " + recupMonth + " - " + recupYear + "<br/>Results processed: " + processedResultCount + "<br/>Total results processed: " + totalResultCount;
pageNum++;
writeMode = "a";
if(processedResultCount === 0) {
pageNum = 1;
recupMonth--;
if(recupMonth === 0 && recupYear > endYear) {
recupMonth = 12;
recupYear--;
}
else if(recupMonth === endMonth && recupYear === endYear) {
alert("Processing finished");
if(totalResultCount != 0) {
contentElt.innerHTML = "Total processed results: " + totalResultCount + '<br/><br/>> Download CSV result file';
}
return;
}
}
when I arrive at the condition
else if(recupMonth === endMonth && recupYear === endYear)
and the condition are satisfied.
Code doesn't go in.
continues to decrement the month and when it gets to -2, it still performs five iteration and then the code arette not offer a CSV download.
I do not understand why it happens like that, someone would have a clue?
else if(recupMonth === endMonth && recupYear === endYear)
Are recupMonth, endMonth, recupYear and endYear the same type? Because may be some of them are strings instead of numbers and the operator "===" is not treating them as equals.
If you are not sure, you can try by parsing them to numbers inside that condition (at least to try if that works):
else if(parseInt(recupMonth, 10) === parseInt(endMonth, 10) && parseInt(recupYear, 10) === parseInt(endYear, 10))
Or trying by not comparing types too:
else if(recupMonth == endMonth && recupYear == endYear)
Hope this helps.
Regards.

JavaScript time greeting?

How do you make something with JavaScript that when your time is below 12 o'clock, it says "good morning!" and when it is after 12 o'clock, it says "good afternoon!"?
Here it is!
var d = new Date();
var time = d.getHours();
if (time < 12) {
document.write("<b>Good morning!</b>");
}
if (time > 12) {
document.write("<b>Good afternoon!</b>");
}
if (time == 12) {
document.write("<b>Go eat lunch!</b>");
}
const date = new Date;
let hours = date.getHours();
let status = (hours < 12)? "Morning" :
((hours <= 18 && hours >= 12 ) ? "Afternoon" : "Night");
console.log(status);
The following should work:
var hours = new Date().hours;
if(hours > 12){
alert("Good Afternoon!");
}
else{
alert("Good Morning!");
}
Just for fun, here's a one liner:
(new Date().hours > 12) ? alert("Good Afternoon!") : alert("Good Morning!");
Working Demo
<SCRIPT LANGUAGE="JavaScript">
currentTime=new Date();
//getHour() function will retrieve the hour from current time
if(currentTime.getHours()<12)
document.write("<b>Good Morning!! </b>");
else if(currentTime.getHours()<17)
document.write("<b>Good Afternoon!! </b>");
else
document.write("<b>Good Evening!! </b>");
</SCRIPT>
//if hour is between 6am-12pm ,print good morning
//if hour is between 12pm-6pm ,print good afternoon
//else good evening
let hour = 5;
if(hour>=6 && hour<12) {
console.log('Good Morning')
}
else if(hour>+12 && hour<18) {
console.log('Good Afternoon')
}
else {
console.log('Good Evening')
}
<script type="text/javascript">
document.write("<h2>");
var day = new Date();
var hr = day.getHours();
if (hr >= 4 && hr < 12) {
document.write("Goedenmorgen");
} else if (hr == 12) {
document.write("Goedemiddag");
} else if (hr >= 12 && hr <= 16) {
document.write("Goedemiddag");
} else if (hr >= 16 && hr <= 23) {
document.write("Goedenavond");
} else {
document.write("Goedennacht");
}
document.write("</h2>");
</script>

Categories