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.
1 Answer 1
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 goesaddHours( -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; };
-
\$\begingroup\$ Thanks for finding the
-0
bug, actually I didn't know-0
was even a number. Also your other points are helpful. \$\endgroup\$Drahcir– Drahcir2014年07月03日 13:29:54 +00:00Commented 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\$200_success– 200_success2014年07月05日 01:12:52 +00:00Commented Jul 5, 2014 at 1:12
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\$