Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created February 18, 2017 14:49
Show Gist options
  • Save vlad-bezden/1b20810c48670077156131c62d1a59d6 to your computer and use it in GitHub Desktop.
Save vlad-bezden/1b20810c48670077156131c62d1a59d6 to your computer and use it in GitHub Desktop.
Time Calculator
<h1 id="result"></h1>
'use strict'
const data = '1:10 12:15 6:43 1:08 4:27 13:09 23 11:50 5:48 8:1 23 2:38 9:44 9:4 8:7 10:56 5:32 11:10 5:15 3:05 6:27 4:39 2:13 16 3:15 4:29 25'
/**
* Converts string representation of hours, minutes and seconds to seconds
*
* @param {string | number} seconds
* @param {string | number} minutes - default 0
* @param {string | number} hours - default 0
* @return {number} - total number of seconds
*/
function toSeconds(seconds, minutes = 0, hours = 0) {
return parseInt(seconds) +
parseInt(minutes) * 60 +
parseInt(hours) * 3600
}
/**
* Pads value with specified number of characters
*
* @param {string} symbol - char that pad value needs to be padded with
* @param {number} length - total length of the string including padding
* @param {number} value - value to be padded
* @return {string} - padded result
*/
function pad(symbol, length) {
return function(value) {
return ((new Array(length)).join(symbol) + value).slice(-length)
}
}
const twoZerosPad = pad('0', 2)
const timePad = (time) => twoZerosPad(time)
/**
* Converts total number of seconds to hours minutes and seconds
*
* @param {number} seconds - total number of seconds
* @return {{hours: number, minutes: number, seconds: number}}
*/
function secondsToTime(seconds) {
return {
hours: Math.floor(seconds / 3600),
minutes: Math.floor((seconds % 3600) / 60),
seconds: seconds % 60
}
}
/**
* Prints out result
* @param {{hours: number, minutes: number, seconds: number}} - time
*/
function print(result) {
const message = `Total time: ${timePad(result.hours)}:${timePad(result.minutes)}:${timePad(result.seconds)}`
console.log(message)
document.querySelector('#result').innerHTML = message
}
const resultInSeconds = data
.split(' ')
.filter(x => x.trim())
.map(t => toSeconds(...t.split(':').reverse()))
.reduce((a, c) => (a += c), 0)
print(secondsToTime(resultInSeconds))

Time Calculator

Calculates total time from string of time, such as '1:10:20 30:05 16' Accepted time: HH:MM:SS, MM:SS, SS. One digit for hours, minutes or seconds is excepted.

A Pen by Vlad Bezden on CodePen.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment