patternjavascriptMinor
Add number of hours to 24 hour clock
Viewed 0 times
numberhourshourclockadd
Problem
This function adds a number of hours to a 24 hour clock:
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.
/**
* @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.
Solution
Tiny question ;)
-
As @Rotora mentioned,
-
-
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
-
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;
};Code Snippets
function sumHours(hours1, hours2){
var sum = (hours1 + hours2) % 24;
return sum < 0 ? 24 + sum : +sum;
};Context
StackExchange Code Review Q#55989, answer score: 5
Revisions (0)
No revisions yet.