Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created April 19, 2016 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/958f77dd045f9e469ca5c0b16f2a314a to your computer and use it in GitHub Desktop.
Save tmcw/958f77dd045f9e469ca5c0b16f2a314a to your computer and use it in GitHub Desktop.
function timestamp (times) {
var intervals = {
h: 60 * 60 * 1000,
m: 60 * 1000,
s: 1000
};
return times.reduce(function(memo, c) {
if (c.match(/[hms]/)) {
memo[memo.length - 1].i = c;
memo.push({ s : '' });
} else if (c.match(/[0-9]/)) {
memo[memo.length - 1].s += c;
} else {
throw new Error('Bad chunk found');
}
return memo;
}, [{ s: '' }]).filter(function(chunk) {
return chunk.s;
}).reduce(function(memo, chunk) {
return memo + Number(chunk.s) * intervals[chunk.i];
}, 0);
}
console.log(timestamp('01h2m5s'.split('')));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment