Rationale for breaking this answer into a function using Javascript -
so doing coderbyte problem earlier today , happy able break down , complete without looking @ answers else completed. however, after completing it, realized way did it, did not build functions. kept calling former variable. question really, necessary use function when answering problem? looking @ big picture, pro's of converting answer mine function ( or pair of functions)
i took number represented full minutes, , broke down hours , minutes. think should easy follow.
var num = 400; var hourdivide = ( num / 60 ); var digits = hourdivide.tostring().split(''); var hour = digits[0] var = 60 * digits[0] var minutes = num - console.log( "you have " + hour + " hours , " + minutes + " minutes left" )
the rationale breaking code function reusability , composability.
let's @ how that code turned useful function
function minutestohours(num) { var hourdivide = ( num / 60 ); var digits = hourdivide.tostring().split(''); var hour = digits[0] var = 60 * digits[0] var minutes = num - almost; return [hour, minutes]; }
this function returns array 2 values in, use in project wanted.
we might not want print same message, turning function allows control outside of actual logic (separation of concerns).
var time = minutestohours(404); console.log("you have", time[0], "hours and", time[1], " minutes left");
using function instead has allowed parameterize code, meaning same few lines of logic can used calculate results given input. particularly useful if start use loops in code.
for(var = 0; < 100; i++) { console.log(minutestohours(i)); }
the alternative have been far less succinct.
another benefit composability comes fact turning code functions form of standardisation. know array function. always have hours in position 0 , minutes in position 1.
we can use write other functions expect style output.
function printtime(time, divider) { var hours = time[0], minutes = time[1]; return [hours, divider, minutes].join(''); }
now can things like:
var time = minutestohours(4041); printtime(time, ':'); // prints "67:21"
Comments
Post a Comment