Created
March 29, 2011 09:30
-
-
Save dolmen/892083 to your computer and use it in GitHub Desktop.
isLeapYear implementation, with a test suite
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
// 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