Skip to content

Instantly share code, notes, and snippets.

@ibolmo
Forked from arian/parseDuration.js
Created February 14, 2012 20:56
Show Gist options
  • Save ibolmo/1830374 to your computer and use it in GitHub Desktop.
Save ibolmo/1830374 to your computer and use it in GitHub Desktop.
(function(){
var re, units = {ms: 1, s: 1e3};
Duration = function(value){
return Duration.parse(value);
};
Duration.parse = function(value){
var match = value.toString().match(re);
return match ? parseFloat(match[1]) * (units[match[2]] || 1) : parseFloat(value)
};
Duration.addUnit = function(keys, multiplier){
Array.from(keys).forEach(function(key){
units[key] = multiplier;
});
re = RegExp('([\d.]+)(' + Object.keys(units).join('|') + ')');
};
// init
Duration.addUnit([]);
})();
console.log(Duration(200));
console.log(Duration('200'));
console.log(Duration('200ms'));
console.log(Duration('.2s'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment