Created
September 4, 2012 04:50
-
-
Save trev/3616700 to your computer and use it in GitHub Desktop.
Date comparison function
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
// How to refactor this bitch? | |
var dateCompare = function(date1, date2, operator) { | |
if(operator === ">") return date1.getTime() > date2.getTime(); | |
if(operator === "<") return date1.getTime() < date2.getTime(); | |
if(operator === "==") return date1.getTime() == date2.getTime(); | |
//And so on and so forth with the other operators (>=, <=) | |
} | |
// Different approach but moves the conditional logic out | |
var dateCompare = function(date1, date2) { | |
return date1.getTime() - date2.getTime(); | |
} | |
// And check logic from from point of call | |
if(dateCompare(dateobj1, dateobj2) < 0) console.log("<") | |
if(dateCompare(dateobj1, dateobj2) < 1) console.log("<=") | |
if(dateCompare(dateobj1, dateobj2) > 0) console.log(">") | |
if(dateCompare(dateobj1, dateobj2) > -1) console.log(">") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment