principlejavascriptMinor
remove redundance in compare-functions
Viewed 0 times
removefunctionscompareredundance
Problem
I wrote some compare-functions that I pass to other methods in javascript:
Is there a way to get this a bit more compact? If I want to add another comparable type I always have to modify the first three functions.
function equal(a, b) {
if (a instanceof Date) return a.getTime() == b.getTime();
return a == b;
}
function lessThan(a, b) {
if (a instanceof Date) return a.getTime() b.getTime();
return a > b;
}
function lessOrEqual(a, b) {
return equal(a, b) || lessThan(a, b);
}
function greaterOrEqual(a, b) {
return equal(a, b) || greaterThan(a, b);
}Is there a way to get this a bit more compact? If I want to add another comparable type I always have to modify the first three functions.
Solution
No need to check if the variables are
instanceof Date. A dates value is its time so when you make (less than/greater than) comparisons with a Date instance (x) you're essentially comparing it to +x or x.valueOf() which will be the same as x.getTime(). Therefore the below will always be equivalent:function equal(a, b) {
if (a instanceof Date && b instanceof Date) return +a == +b; //compare the 2 dates times as noted in the above statement +x == x.getTime() == x.valueOf()
return a == b;
}
function lessThan(a, b) {
return a b;
}Code Snippets
function equal(a, b) {
if (a instanceof Date && b instanceof Date) return +a == +b; //compare the 2 dates times as noted in the above statement +x == x.getTime() == x.valueOf()
return a == b;
}
function lessThan(a, b) {
return a < b;
}
function greaterThan(a, b) {
return a > b;
}Context
StackExchange Code Review Q#43518, answer score: 3
Revisions (0)
No revisions yet.