Skip to content

Instantly share code, notes, and snippets.

@matsuby
Last active October 16, 2018 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsuby/fb96ea99539801e2049a955e555cbd74 to your computer and use it in GitHub Desktop.
Save matsuby/fb96ea99539801e2049a955e555cbd74 to your computer and use it in GitHub Desktop.
JavaScript one-liner function: isLeapYear (Proleptic Gregorian calendar)
// =================================================================
// 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