6
\$\begingroup\$

This function adds a number of hours to a 24 hour clock:

/**
 * @param {Integer} now The current hours
 * @param {Integer} add The number of hours to add
 */
function addHours(now, add){
 var h = (now + add) % 24;
 return h < 0 ? 24 + h : h;
};
  • addHours(2, 5) //7
  • addHours(23, 5) //4
  • addHours(23, -5) //18
  • addHours(72, 3) //3
  • addHours(0, 0) //0

The output should always be an integer in the range of 0 - 23.

I can't see any problem with it, but maybe you can. Please let me know if it can be improved or if there are any bugs.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jul 3, 2014 at 12:19
\$\endgroup\$
2
  • \$\begingroup\$ Other that the inappropriate parameter name now, there is not much you could say about it code-wise. However what I'd like to question its usefulness, which seems very limited. \$\endgroup\$ Commented Jul 3, 2014 at 13:02
  • \$\begingroup\$ @RoToRa I'm using as part of a set of unit tests. I have to test some other functions that manipulate time, and this one helps keep the tests readable. \$\endgroup\$ Commented Jul 3, 2014 at 13:17

1 Answer 1

5
\$\begingroup\$

Tiny question ;)

  • As @Rotora mentioned, now is not a fantastic parameter name, it conveys that I need to only pass who late it is 'now', add is a verb, also not brilliant as parameter naming goes

  • addHours( -500 , -100 ) returns -0, is that what you want ?

  • You have 4 lines of comment, 3 lines of code, 1 blank line, perhaps you have to much comment ? Try to not need comments by working harder on parameter names.

  • Since adding is commutative ( order does not matter ), I would consider naming the function sumHours and name the parameters hours1 and hours2

    function sumHours(hours1, hours2){
     var sum = (hours1 + hours2) % 24;
     return sum < 0 ? 24 + sum : +sum;
    };
    
answered Jul 3, 2014 at 13:23
\$\endgroup\$
2
  • \$\begingroup\$ Thanks for finding the -0 bug, actually I didn't know -0 was even a number. Also your other points are helpful. \$\endgroup\$ Commented Jul 3, 2014 at 13:29
  • \$\begingroup\$ Negative zero might not be that big of a problem for you, as it behaves very much like positive zero. You would have to go out of your way to test 1 / -0 === Number.NEGATIVE_INFINITY to detect negative zero. \$\endgroup\$ Commented Jul 5, 2014 at 1:12

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.