Radicate
Radicate

Reputation: 3034

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);
}

Upvotes: 0

Views: 91

Answers (3)

Arnauld
Arnauld

Reputation: 6110

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);

Upvotes: 3

robertklep
robertklep

Reputation: 203304

And another one:

let ms = str.split(':').reduce((a,v,i) => a + v * [3600000, 60000, 1000, 1][i], 0)

EDIT, thanks to @Swonkie:

let ms = str.split(':').reduce((a,v,i) => a + v * [3600000, 60000, 1000][i], 0)

Which leads to (thanks @Arnauld):

let ms = str.split(':').reduce((a,v,i)=>a+v*1E3*[3600,60,1][i],0);

Or, with rounding (not at all tested for validity):

let ms = str.split(':').reduce((a,v,i)=>a+v*1E3*[3600,60,1][i],0.5)|0;

Upvotes: 2

Adam Fischer
Adam Fischer

Reputation: 1100

As described here:

https://codereview.stackexchange.com/questions/45335/milliseconds-to-time-string-time-string-to-milliseconds

this looks like good solution:

function timeString2ms(a,b){// time(HH:MM:SS.mss) // optimized
 return a=a.split('.'), // optimized
  b=a[1]*1||0, // optimized
  a=a[0].split(':'),
  b+(a[2]?a[0]*3600+a[1]*60+a[2]*1:a[1]?a[0]*60+a[1]*1:a[0]*1)*1e3 // optimized
}

"oneline solution"

function timeString2ms2(a,b){ return a=a.split('.'),b=a[1]*1||0,a=a[0].split(':'),b+(a[2]?a[0]*3600+a[1]*60+a[2]*1:a[1]?a[0]*60+a[1]*1:a[0]*1)*1e3 }

Usage

console.log(timeString2ms('10:21:32.093')); // hh:mm:ss.mss
console.log(timeString2ms('21:32.093')); // mm:ss.mss
console.log(timeString2ms('21:32')); // mm:ss
console.log(timeString2ms('32.093')); // ss.mss 
console.log(timeString2ms('32')); // ss
console.log(timeString2ms('32467.784'));  // seconds.ms
console.log(timeString2ms(32467.784+'')); // seconds.ms

Upvotes: -1

Related Questions