JavaScript leap year check
basis
years are 365,2425 days long, so leap years are every 4, except every 100, except every 400
code
function leapYear(a) {
// return !(a%4) && ( !!(a%100) || !(a%400) );
return !(a&3) && ( !!(a%25) || !(a&15) );
}
example
evidence
explanation
mind:
- your operators and their precedences
- short-circuit evaluation, shown
as such
- a%4 === a&3, but the latter’s faster
- a%25 is a reduction of a%100 (when a%4 is already accounted for)
- makes no difference to the computer, but shows the work (25*16=400), and feels fun 🤓
- a%16 is a reduction of a%400 (when a%4 is already accounted for)
- quite important, because it leads to the following:
- a%16 === a&15, but the latter’s faster
- yes, i’m aware that a&12 can be used in this specific case—only the bitmask of 1100 is needed
- my proclivity for 12 notwithstanding, i agree that this obfuscation of 25*16=400 does no favours
- Double NOT (!!) is a shortcut to force a value to its boolean
so:
- if none match (e.g., 1995):
- return !(1995&3) && ( !!(1995%25) || !(1995&15) );
- return !(3) && ( !!(1995%25) || !(1995&15) );
- return false &&
( !!(1995%25) || !(1995&15) );
- return false;
- if%4 (e.g., 1996):
- return !(1996&3) && ( !!(1996%25) || !(1996&15) );
- return !(0) && ( !!(1996%25) || !(1996&15) );
- return true && ( !!(1996%25) || !(1996&15) );
- return true && ( !!(21) || !(1996&15) );
- return true && ( true ||
!(1996&15) );
- return true && true;
- return true;
- if%25 (e.g., 1900):
- return !(1900&3) && ( !!(1900%25) || !(1900&15) );
- return !(0) && ( !!(1900%25) || !(1900&15) );
- return true && ( !!(1900%25) || !(1900&15) );
- return true && ( !!(0) || !(1900&15) );
- return true && ( false || !(1900&15) );
- return true && ( false || !(12) );
- return true && ( false || false );
- return true && false;
- return false;
- if%400 (e.g., 2000):
- return !(2000&3) && ( !!(2000%25) || !(2000&15) );
- return !(0) && ( !!(2000%25) || !(2000&15) );
- return true && ( !!(2000%25) || !(2000&15) );
- return true && ( !!(0) || !(2000&15) );
- return true && ( false || !(2000&15) );
- return true && ( false || !(0) );
- return true && ( false || true );
- return true && true;
- return true;