I am trying to learn functional programming in JavaScript, and saw a little task on Twitter that I wanted to have a go at:
var durations = ["12:38", "6:36", "9:03", "8:34", "5:02", "6:54", "13:22", "4:41", "8:36", "21:58", "3:06", "10:46", "10:13", "12:54", "14:00", "11:03", "16:03", "10:52", "24:53", "10:03", "11:49", "15:47", "3:19", "2:06", "5:47", "1:03", "5:29", "5:47", "26:39"]; // Above is a list of video lengths, how long are all the videos together? // write a function that will take the above array of string durations and convert it hours/mins/seconds // You can use any JS you want - loops/map/reduce/etc...
It would be great to have some feedback on how this could be refined further or improved.
var hours = 0, minutes = 0, seconds = 0;
function sumArrayIndex(array, i, separator) {
return array
.map(x => x.split(separator)
.map(c => { return parseInt(c) })
)
.map(x => { return x[i]; })
.reduce((x, y) => { return x += y }, 0);
}
function minToSec(m) {
return m * 60
}
function tallyTime(s) {
var hrs = 0;
var min = Math.floor(s / 60);
var sec = parseInt(s % 60, 16);
if (min > 59) {
hrs = Math.floor(min / 60);
min = min % 60;
}
hours += hrs;
minutes += min;
seconds += sec;
}
function outputTime() {
return hours + ':' + minutes + ':' + seconds;
}
var tally = tallyTime(minToSec(sumArrayIndex(durations, 0, ':')) + sumArrayIndex(durations, 1, ':'));
console.log(outputTime(tally));