Skip to content

Instantly share code, notes, and snippets.

@dolmen
Created March 29, 2011 09:30
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 dolmen/892083 to your computer and use it in GitHub Desktop.
Save dolmen/892083 to your computer and use it in GitHub Desktop.
isLeapYear implementation, with a test suite
// See http://stackoverflow.com/questions/61088/hidden-features-of-javascript/64950#64950
function isLeapYear(year) {
return !(year % 4 != 0 || (year % 100 == 0 && year % 400 != 0));
}
function isLeapYear_refButSlow(year) {
return new Date(year, 1, 29, 0, 0).getMonth() != 2;
}
var range = (function() {
var undef;
var forEach = function(func) {
var cur;
while ((cur = this()) !== undef)
func(cur);
};
return function(from, to, step) {
var f;
if (to > from) {
if (step === undef) u = 1;
f = function() {
if (from > to) return undef;
var cur = from;
from += step;
return cur;
};
} else {
if (step === undef) undef = -1;
f = function() {
if (from < to) return undef;
var cur = from;
from += step;
return cur;
};
}
f.forEach = forEach;
return f;
}
})();
function test(year) {
WScript.Echo(year+": "+(isLeapYear(year) == isLeapYear_refButSlow(year) ? "OK" : "Err"));
}
range(1500, 2400, 100).forEach(test);
range(1970, 2011, 1).forEach(test);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment