UNPKG

pomeranian-durations

Version:

An immutable duration library based on the ISO-8601 format for durations.

52 lines (39 loc) 2.63 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.normalizeTime = void 0; var _constants = require("./constants"); var _transformations = require("./transformations"); var _conversions = require("./conversions"); var _validate = require("./validate"); var _utils = require("./_utils"); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var TIME_UNITS = [_constants.UNIT_NAMES.hours, _constants.UNIT_NAMES.minutes, _constants.UNIT_NAMES.seconds]; /** * Normalizes the time part of an iso8601 duration. * @param isoString {string} - an ISO8601 duration * @returns isoString {string} - an ISO8601 duration * @example * normalizeTime('P1DT1234S') // => 'P1DT20M34S' * @example * normalizeTime('PT1S') // => 'PT1S' */ var normalizeTime = function normalizeTime(isoString) { if ((0, _validate.isInvalid)(isoString)) { return _constants.INVALID_DURATION; } var fragments = (0, _transformations.toFragments)(isoString); var microseconds = (0, _utils.pipe)(fragments, (0, _utils.pick)(TIME_UNITS), _transformations.toIso, _conversions.asMicroseconds); var hours = Math.floor(microseconds / _constants.ONE_HOUR); var minutes = Math.floor((microseconds - hours * _constants.ONE_HOUR) / _constants.ONE_MINUTE); var seconds = (microseconds - hours * _constants.ONE_HOUR - minutes * _constants.ONE_MINUTE) / _constants.ONE_SECOND; return (0, _transformations.toIso)(_objectSpread(_objectSpread({}, fragments), {}, { hours: hours, minutes: minutes, seconds: seconds })); }; exports.normalizeTime = normalizeTime;