本文基于我对 ms 这个库的阅读。这个库的代码一共一百多行,完整看下来也就十几分钟,但是这个库非常的有用。这个库的核心是,将毫秒和可读的表示时间的字符串相互转换。这个库还是存在一些缺陷,比如在毫秒转字符串时用了近似(其实也不算是缺陷,而是有意为之)。
首先定义几个常量,分别为一秒,一分,一时,一日,一年对应的毫秒数。
var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24,
y = d * 365.25
然后我们写字符串转毫秒的方法
function parse(str){
var arr = str.split(' '),
res = 0
arr.forEach(function(a){
var match = /^((?:\d+)?\.?\d+) *(y|d|h|m|s|ms)?$/i.exec(a)
var n = parseFloat(match[1]);
var type = match[2].toLowerCase();
switch(type){
case 'y':
res += n*y;
break;
case 'd':
res += n*d;
break;
case 'h':
res += n*h;
break;
case 'm':
res += n*m;
break;
case 's':
res += n*s;
break;
case 'ms':
res += n;
}
})
return res
}
测试一下
parse('2d 10h 5s') //208805000
然后我们写毫秒转字符串的方法
function tostr(ms){
if(ms === 0) return "";
if(ms >= d) return Math.round(ms / d)+'d ' + tostr(ms%d);
if(ms >= h) return Math.round(ms / h)+'h ' + tostr(ms%h);
if(ms >= m) return Math.round(ms / m)+'m ' + tostr(ms%m);
if(ms >= s) return Math.round(ms / s)+'s ' + tostr(ms%s);
return ms + 'ms';
}
console.log(tostr(610000000))
封装
这么多全局变量实在太糟糕,用IIFE封装一下
var ms = (function(){
var s = 1000,
m = s*60,
h = m*60,
d = h*24,
y = d*365.25
function parse(str){
var arr = str.split(' '),
res = 0
arr.forEach(function(a){
var match = /^((?:\d+)?\.?\d+) *(y|d|h|m|s|ms)?$/i.exec(a)
var n = parseFloat(match[1]);
var type = match[2].toLowerCase();
switch(type){
case 'y':
res += n*y;
break;
case 'd':
res += n*d;
break;
case 'h':
res += n*h;
break;
case 'm':
res += n*m;
break;
case 's':
res += n*s;
break;
case 'ms':
res += n;
}
})
return res
}
function tostr(ms){
if(ms === 0) return "";
if(ms >= d) return Math.round(ms / d)+'d ' + tostr(ms%d);
if(ms >= h) return Math.round(ms / h)+'h ' + tostr(ms%h);
if(ms >= m) return Math.round(ms / m)+'m ' + tostr(ms%m);
if(ms >= s) return Math.round(ms / s)+'s ' + tostr(ms%s);
return ms + 'ms';
}
return function(val, options){
options = options || {};
if ('string' == typeof val) return parse(val);
return tostr(val);
};
})()
网友评论