All files / time parseUnit.js

100% Statements 25/25
50% Branches 4/8
100% Functions 1/1
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64                              1x 1x   1x               1x       1x 1x 1x 1x 1x 1x   1x 1x 1x     1x 1x 1x     1x 1x 1x     1x 1x 1x     1x   1x     1x  
/**
 * 时间数字拆分为天时分秒
 * @method time/parseUnit
 * @param {Number} time 毫秒数
 * @param {Object} spec 选项
 * @param {String} [spec.maxUnit='day'] 拆分时间的最大单位,可选 ['day', 'hour', 'minute', 'second']
 * @returns {Object} 拆分完成的天时分秒
 * @example
 * var $parseUnit = require('@spore-ui/kit/packages/time/parseUnit');
 * console.info( $parseUnit(12345 * 67890) );
 * // Object {day: 9, hour: 16, minute: 48, second: 22, ms: 50}
 * console.info( $parseUnit(12345 * 67890, {maxUnit : 'hour'}) );
 * // Object {hour: 232, minute: 48, second: 22, ms: 50}
 */
 
var $numerical = require('../num/numerical');
var $assign = require('../obj/assign');
 
var UNIT = {
  day: 24 * 60 * 60 * 1000,
  hour: 60 * 60 * 1000,
  minute: 60 * 1000,
  second: 1000,
};
 
function parseUnit(time, spec) {
  var conf = $assign({
    maxUnit: 'day',
  }, spec);
 
  var data = {};
  var maxUnit = $numerical(UNIT[conf.maxUnit]);
  var uDay = UNIT.day;
  var uHour = UNIT.hour;
  var uMinute = UNIT.minute;
  var uSecond = UNIT.second;
 
  Eif (maxUnit >= uDay) {
    time = $numerical(time);
    data.day = Math.floor(time / uDay);
  }
 
  Eif (maxUnit >= uHour) {
    time -= $numerical(data.day * uDay);
    data.hour = Math.floor(time / uHour);
  }
 
  Eif (maxUnit >= uMinute) {
    time -= $numerical(data.hour * uHour);
    data.minute = Math.floor(time / uMinute);
  }
 
  Eif (maxUnit >= uSecond) {
    time -= $numerical(data.minute * uMinute);
    data.second = Math.floor(time / uSecond);
  }
 
  data.ms = time - data.second * uSecond;
 
  return data;
}
 
module.exports = parseUnit;