5
\$\begingroup\$

I wrote some compare-functions that I pass to other methods in javascript:

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 greaterThan(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.

\$\endgroup\$
3
\$\begingroup\$

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;
}

function greaterThan(a, b) {
    return a > b;
}
\$\endgroup\$
  • \$\begingroup\$ new Date("2014-03-05") == new Date("2014-03-05") and new Date("2014-03-05").getTime() == new Date("2014-03-05").getTime() are not the same. \$\endgroup\$ – user2033412 Mar 5 '14 at 15:27
  • \$\begingroup\$ new Date("2014-03-05") == new Date("2014-03-05") returns false \$\endgroup\$ – user2033412 Mar 5 '14 at 15:28
  • \$\begingroup\$ @user2033412 ah you're right for that case \$\endgroup\$ – megawac Mar 5 '14 at 15:28
  • \$\begingroup\$ I like your new approach, now I can just write plus before every variable inside the functions and get rid of the typecheck. \$\endgroup\$ – user2033412 Mar 5 '14 at 15:32
  • 1
    \$\begingroup\$ Perfect! I'll go for +a === +b and overriding valueOf \$\endgroup\$ – user2033412 Mar 5 '14 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.