Last active
October 16, 2018 18:10
-
-
Save matsuby/fb96ea99539801e2049a955e555cbd74 to your computer and use it in GitHub Desktop.
JavaScript one-liner function: isLeapYear (Proleptic Gregorian calendar)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ================================================================= | |
// https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar | |
// ================================================================= | |
// for ES2015 | |
{ | |
const isLeapYear = y => !!(+y===parseInt(y)&&!y.pop&&(y%4)^(y%100)|!(y%400)); | |
const testParams = [ | |
// expect: true (is leap) | |
0, 4, 400, -4, | |
"0", "4", "400", "-4", | |
// expect: false (is not leap) | |
1, 100, -1, 4.1, | |
"1", "100", "-1", "4.1", | |
// expect: false (invalid) | |
"4test", {a:4}, [4], [400], | |
"", true, false, null, undefined, NaN, | |
]; | |
for (p of testParams) { | |
const t = p !== p ? p : JSON.stringify(p); | |
console.log(`${t}: ${isLeapYear(p)}`); | |
} | |
} | |
// for ES5 | |
(function() { | |
var isLeapYear = function(y) { | |
return !!(+y===parseInt(y)&&!y.pop&&(y%4)^(y%100)|!(y%400)); | |
}; | |
var testParams = [ | |
// expect: true (is leap) | |
0, 4, 400, -4, | |
"0", "4", "400", "-4", | |
// expect: false (is not leap) | |
1, 100, -1, 4.1, | |
"1", "100", "-1", "4.1", | |
// expect: false (invalid) | |
"4test", {a:4}, [4], [400], | |
"", true, false, null, undefined, NaN, | |
]; | |
testParams.forEach(p => { | |
var t = p !== p ? p : JSON.stringify(p); | |
console.log(t + ": " + isLeapYear(p)); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment