Radicate Radicate - 3 months ago 13
Javascript Question

Efficiently convert string based time into milliseconds

I was given a challenge, to create a function that'd convert a string based time into milliseconds.

That's the string format I was given:


"hours:minutes:seconds.milliseconds"


So this value for example will need to return 3010220.


"0:50:10.220"


The function needs to be short and one lined.
I'd love to know where I could improve the function below as it didn't pass the criteria. how can this be turned into a one liner?

function toMilliseconds(time){
return time.match(/[0-9]+/g).map(function(val,s,a){
return s != 3 ? +val * ((Math.pow(60,a.length - s -2) * 1000)) : +val;
}).reduce(function(a,b){
return a+b;
},0);
}

Answer

There are many different ways.

This is the shortest way I can think of (using ES6):

var str = "0:50:10.220";

var ms = (s=>1E3*s[2]+6E4*s[1]+36E5*s[0])(str.split(':'));

console.log(ms);