I am on codewars, here is the challenge:
Given a month as an integer from 1 to 12, return to which quarter of the year it belongs as an integer number.
For example: month 2 (February), is part of the first quarter; month 6 (June), is part of the second quarter; and month 11 (November), is part of the fourth quarter.
Here is what I tried:
const quarterOf = (month) => {
// Your code here
if (month <= 3) {
return 1
} else if (6 >= month > 3) {
return 2
} else if (9 >= month > 6) {
return 3
} else if (12 >= month > 9) {
return 4
}
}
This doesn't seem to work, I know I could assign each month a variable, but I'm trying to improve my skills, can someone explain why this does not work to me?
All you need is
const quarterOf = (month) =>
{
if (month <= 3) return 1
if (month <= 6) return 2
if (month <= 9) return 3
return 4
}
or
const quarterOf = month => Math.ceil(month / 3);
This is simple you are trying to check for two conditions in one statement try to use && and || for separation of conditions your code will look like this:
const quarterOf = (month) => {
// Your code here
if (month <= 3) {
return 1
} else if (6 >= month && month > 3) {
return 2
} else if (9 >= month && month > 6) {
return 3
} else if (12 >= month && month > 9) {
return 4
}
}
This question already has answers here:
Check if a value is within a range of numbers
(8 answers)
Closed 10 months ago.
beginning in coding, I'm trying to build a function that asks the user to enter a value for hour then for minutes and return an array showing clock one minute later, but it isn't working 😢 I tried to fix it for some hours now and am really stuck, could anyone tell me where am wrong please?
let hour = window.prompt("Enter hour", "");
let minutes = window.prompt("Enter minutes", "");
function clock(hour, minutes) {
let arr = [];
if(0 <= hour < 23 && 0 <= minutes < 59) {
arr.push(hour, minutes + 1);
} else if((minutes == 59) && (hour == 23)){
arr.push(0, 0);
}
return arr;
}
clock();
console.log(clock(23, 59));// Got [23, 60] ❌ should return [0, 0]
console.log(clock(15, 3));// Got [15, 4] ✅
Thanks for answering, here is the clean code
function clock(hour, minutes) {
let arr = [];
if(0 <= minutes && minutes < 59) {
arr.push(hour, minutes + 1);
} else if(minutes == 59){
arr.push(hour + 1, 0);
if(hour == 23){
arr.push(0, 0);
}
}
return arr;
}
clock();
console.log(clock(13, 27)); // returns [13, 28];
console.log(clock(13, 59)); // returns [14, 0];
I don't think you can do this: 0 <= hour < 23 && 0 <= minutes < 59
It should be: 0 <= hour && hour < 23 && 0 <= minutes && minutes < 59
I'm trying to determine whether a year is a leap year or not. I'm not sure where i'm missing something because this code is meant to determine that.
Thanks for your help.
let Year = (year) => {
this.year = year;
};
Year.prototype.isLeap = () => {
return (
this.year % 400 === 0 ||
(this.year % 4 === 0 && (this.year % 100 === 0))
);
};
let year = new Year(2014);
year.isLeap();
Thanks I've figured it out.
Initially i did it will the kind of If statement you guys are pointing to here!, so I'm now refactoring to av a cleaner code.
My code was having issue on this line
(this.year % 4 === 0 && (this.year % 100 === 0))
the right syntax is
(this.year % 4 === 0 && !(this.year % 100 === 0))
You could just check the feburary 29th of the given year and see if its changes to march 1st.
const date = new Date(this.year, 1, 29);
return date.getMonth() === 1;
If getMonth() returns 1, then its still feburary which means its leap year.
Number.prototype.isLeap = function() {
return !(this % 4 || !(this % 100) && this % 400);
}
let year = 2000;
console.log(year.isLeap()); // prints true
year = 1900;
console.log(year.isLeap()); // prints false
year = 1904;
console.log(year.isLeap()); // prints true
year = 2003;
console.log(year.isLeap()); // prints false
The following code block will work well on Javascript and also on Typescript if you remove the function keyword. To understand the logic behind this implementation have a look at this link How to determine whether a year is a leap year.
function isLeapYear(year) {
let isLeapObj = {};
if ((year % 4 === 0 && year % 100 != 0) || year % 400 === 0) {
isLeapObj['isLeap'] = true;
isLeapObj['days'] = 366;
} else {
isLeapObj['isLeap'] = false;
isLeapObj['days'] = 365;
}
return isLeapObj;
}
x = isLeapYear(2020);
console.log(x);
For Javscript use the following code
In regards to #brenjt's answer above you might want to change the value 29 to 30
const date = new Date(this.year, 1, 30);
if (date.getMonth() === 1) {
console.log("it's not a leap year");
} else {
console.log("it's a leap year");
}
How can I get the code below to work when I have a month of february? Currently it is getting to the day and then stopping before getting to the if to determine whether it is a leap year.
if (month == 2) {
if (day == 29) {
if (year % 4 != 0 || year % 100 == 0 && year % 400 != 0) {
field.focus();
field.value = month +'/' + '';
}
}
else if (day > 28) {
field.focus();
field.value = month +'/' + '';
}
}
It's safer to use Date objects for datetime stuff, e.g.
isLeap = new Date(year, 1, 29).getMonth() == 1
Since people keep asking about how exactly this works, it has to do with how JS calculates the date value from year-month-day (details here). Basically, it first calculates the first of the month and then adds N -1 days to it. So when we're asking for the 29th Feb on a non-leap year, the result will be the 1st Feb + 28 days = 1st March:
> new Date(2015, 1, 29)
< Sun Mar 01 2015 00:00:00 GMT+0100 (CET)
On a leap year, the 1st + 28 = 29th Feb:
> new Date(2016, 1, 29)
< Mon Feb 29 2016 00:00:00 GMT+0100 (CET)
In the code above, I set the date to 29th Feb and look if a roll-over took place. If not (the month is still 1, i.e. February), this is a leap year, otherwise a non-leap one.
Compared to using new Date() this is is around 100 times faster!
Update:
This latest version uses a bit test of the bottom 3 bits (is it a multiple of 4), as well as a check for the year being a multiple of 16 (bottom 4 bits in binary is 15) and being a multiple of 25.
ily = function(y) {return !(y & 3 || !(y % 25) && y & 15);};
http://jsperf.com/ily/15
It is slightly faster again than my previous version (below):
ily = function(yr) {return !((yr % 4) || (!(yr % 100) && (yr % 400)));};
http://jsperf.com/ily/7
It is also 5% faster, compared to the already fast conditional operator version by broc.seib
Speed Test results: http://jsperf.com/ily/6
Expected logic test results:
alert(ily(1900)); // false
alert(ily(2000)); // true
alert(ily(2001)); // false
alert(ily(2002)); // false
alert(ily(2003)); // false
alert(ily(2004)); // true
alert(ily(2100)); // false
alert(ily(2400)); // true
isLeap = !(new Date(year, 1, 29).getMonth()-1)
...subtraction by one should work even faster than compare on most CPU architectures.
Correct and Fast:
ily = function(yr) { return (yr%400)?((yr%100)?((yr%4)?false:true):false):true; }
If you are in a loop or counting the nanoseconds, this is two magnitudes faster than running your year through a new Date() object. Compare the performance here: http://jsperf.com/ily
Better historical computation of leap years.
The code below takes into account that leap years were introduced in 45BC with the Julian calendar, and that the majority of the Western world adopted the Gregorian calendar in 1582CE, and that 0CE = 1BC.
isLeap = function(yr) {
if (yr > 1582) return !((yr % 4) || (!(yr % 100) && (yr % 400)));
if (yr >= 0) return !(yr % 4);
if (yr >= -45) return !((yr + 1) % 4);
return false;
};
Britain and its colonies adopted the Gregorian calendar in 1752, so if you are more Anglo centric this version is better (We'll assume Britain adopted the Julian calendar with Roman conquest starting in 43CE).
isLeap = function(yr) {
if (yr > 1752) return !((yr % 4) || (!(yr % 100) && (yr % 400)));
if (yr >= 43) return !(yr % 4);
return false;
};
JavaScript is expected to be getting a new Date/Time API which exposes a new global object - Temporal. This global object provides JS devs with a nicer way to deal with dates/times. It is currently a stage 3 proposal and should hopefully be available for use shortly.
The temporal api exposes a nice property for checking for leap years - inLeapYear. This returns true if a particular date is a leap year, otherwise false. Below we're using with() to convert the date returned by plainDateISO to one with our particular year:
const isLeap = year => Temporal.now.plainDateISO().with({year}).inLeapYear;
console.log(isLeap(2020)); // true
console.log(isLeap(2000)); // true
console.log(isLeap(1944)); // true
console.log(isLeap(2021)); // false
console.log(isLeap(1999)); // false
If you just want to check if your current system date time is a leap year, you can omit the .with():
// true if this year is a leap year, false if it's not a leap year
const isLeap = Temporal.now.plainDateISO().inLeapYear;
I use this because I hate having to keep referring to January as 0 and February as 1.
To me and PHP and readable dates, February=2. I know it doesn't really matter as the number never changes but it just keeps my brain thinking the same across different code.
var year = 2012;
var isLeap = new Date(year,2,1,-1).getDate()==29;
You can easily make this to work calling .isLeapYear() from momentjs:
var notLeapYear = moment('2018-02-29')
console.log(notLeapYear.isLeapYear()); // false
var leapYear = moment('2020-02-29')
console.log(leapYear.isLeapYear()); // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
all in one line 😉
const isLeapYear = (year) => (year % 100 === 0 ? year % 400 === 0 : year % 4 === 0);
console.log(isLeapYear(2016)); // true
console.log(isLeapYear(2000)); // true
console.log(isLeapYear(1700)); // false
console.log(isLeapYear(1800)); // false
console.log(isLeapYear(2020)); // true
function isLeap(year) {
if ( (year % 4 === 0 && year % 100 !== 0) || (year % 4 === 0 && year % 100 === 0 && year % 400 === 0) ) {
return 'Leap year.'
} else {
return 'Not leap year.';
}
}
Pseudo code
if year is not divisible by 4 then not leap year
else if year is not divisible by 100 then leap year
else if year is divisible by 400 then leap year
else not leap year
JavaScript
function isLeapYear (year) {
return year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 )
}
Using the above code insures you do only one check per year if the year is not divisible by 4
Just by adding the brackets you save 2 checks per year that is not divisible by 4
Another alternative is to see if that year has the date of February 29th. If it does have this date, then you know it is a leap year.
ES6
// Months are zero-based integers between 0 and 11, where Febuary = 1
const isLeapYear = year => new Date(year, 1, 29).getDate() === 29;
Tests
> isLeapYear(2016);
< true
> isLeapYear(2019);
< false
function leapYear(year){
if((year%4==0) && (year%100 !==0) || (year%400==0)){
return true;
}
else{
return false;
}
}
var result = leapYear(1700);
console.log(result);
Alternative non-conditionals solution:
const leapYear = y => (y % 4 === 0) + (y % 100 !== 0) + (y % 400 === 0) === 2
Use this:
Date.prototype.isLeap = function() {
return new Date(this.getFullYear(), 1, 29).getMonth() == 1;
};
Date.prototype.isLeap = function() {
return new Date(this.getFullYear(), 1, 29).getMonth() == 1;
};
console.log(new Date("10 Jan 2020").isLeap()); // True
console.log(new Date("10 Jan 2022").isLeap()); // False
I'm displaying a message between Saturday at 6pm and Sunday 4am. The last time I had to do this it didn't work because I didn't take into account UTC time going negative when changing it to NYC time.
I am doing the math right (displaying at the appropriate times)?Should I put the UTC conversion code into its own function? Is this the worst js you've ever seen?
-- jquery is called --
$(document).ready(function() {
var dayTime = new Date();
var day = dayTime.getUTCDay();
var hour = dayTime.getUTCHours();
//alert(day.toString()+" "+hour.toString());
if (hour >= 5){
hour = hour-5;
}
else{
hour = hour+19;
if(day > 0){
day--;
}
else{
day = 6;
}
}
//alert(day.toString()+" "+hour.toString());
if ((day == 6 && hour >= 18) || (day == 0 && hour < 4)){
}
else{
$('#warning').hide(); //Want this message to show if js is disabled as well
}
});
Why do you even need that UTC stuff? Just work with local time:
var day = dayTime.getDay();
var hour = dayTime.getHours();
And you can clean up that conditional a bit too:
if (!(day == 6 && hour >= 18) && !(day == 0 && hour < 4)) {
$('#warning').hide();
}
This should get you your server's time:
var dayTime = new Date();
localOffset = dayTime.getTimezoneOffset() * 60000;
serverOffset = 5 * 60 * 60000;
dayTime = new Date(dayTime.getTime() + (localOffset - serverOffset));
Play around with that "5" in the server offset; it's the hours. It may need to be a -5; I'm not really sure.
Also, that's going to break every daylight savings. You'll have to detect that somehow and modify serverOffset.