Skip to content

Instantly share code, notes, and snippets.

@jastuccio
Last active December 5, 2016 00:55
Show Gist options
  • Save jastuccio/81c99056eb72acfade5079bbda08a969 to your computer and use it in GitHub Desktop.
Save jastuccio/81c99056eb72acfade5079bbda08a969 to your computer and use it in GitHub Desktop.
JavaScript Challenge
<div>The total time of the movies is: <span id="demo"></span>
</div>
// http://codepen.io/jastuccio/pen/RoQqvV?editors=1011
// https://codepen.io/wesbos/pen/bVMKod
// 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...
//
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"];
var test = ["59:01","1:01","1:01" ];
function combinedLength(arr, minutes) {
// create an array of minutes
var seconds = [];
var minutes = [];
var len = arr.length;
for (var i = 0; i < len; i++) {
seconds.push( parseInt( arr[i].match(/\d{2}$/g )) );
minutes.push( parseInt( arr[i].match(/^\d{1,2}/g )) );
}
// sum the arrays of minutes and seconds return an integer
seconds = seconds.reduce(function(a, b) { return a + b; } );
minutes = minutes.reduce(function(a, b) { return a + b; } );
// convert seconds to minutes
var convertedMinutes= Math.trunc( seconds / 60);
var seconds = seconds % 60;
// convert minutes to hours and minutes
var hours = Math.trunc( (minutes + convertedMinutes) / 60);
var minutes = ((minutes + convertedMinutes) % 60) ;
// Add a leading zero to seconds if needed
if( seconds < 10 ){
seconds = ("0" + seconds).slice(-2);
}
console.log(hours +":"+ minutes +":"+ seconds);
document.getElementById('demo').innerHTML = hours +":"+ minutes +":"+ seconds;
}
combinedLength(test);
combinedLength(durations);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment