pomeranian-durations
Version:
An immutable duration library based on the ISO-8601 format for durations.
82 lines (75 loc) • 2.77 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.format = void 0;
var _utils = require("./_utils");
var _find = require("./find");
/**
* Helpers to format an iso duration. Available tokens are:
*
* | Token | Unit | Result example |
* |---------|----------|------------------|
* | %Y | years | 0, 1, ..., 112 |
* | %YY | years | 00, 01, ..., 112 |
* | %M' | months | 0, 1, ..., 112 |
* | %MM | months | 00, 01, ..., 112 |
* | %W | weeks | 0, 1, ..., 112 |
* | %WW | weeks | 00, 01, ..., 112 |
* | %D | days | 0, 1, ..., 112 |
* | %DD | days | 00, 01, ..., 112 |
* | %h | hours | 0, 1, ..., 112 |
* | %hh | hours | 00, 01, ..., 112 |
* | %m | minutes | 0, 1, ..., 112 |
* | %mm | minutes | 00, 01, ..., 112 |
* | %s | seconds | 0, 1, ..., 112 |
* | %ss | seconds | 00, 01, ..., 112 |
*
* @name default
*/
var compose = function compose() {
for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
fns[_key] = arguments[_key];
}
return function (initialValue) {
return fns.reduce(function (result, fn) {
return fn(result);
}, initialValue);
};
};
var toPaddedString = (0, _utils.curry)(function (number, value) {
return "".concat((0, _utils.leftPad)(number, '0', value));
});
var TOKEN = {
'%Y': compose(_find.findYears, toPaddedString(1)),
'%YY': compose(_find.findYears, toPaddedString(2)),
'%M': compose(_find.findMonths, toPaddedString(1)),
'%MM': compose(_find.findMonths, toPaddedString(2)),
'%W': compose(_find.findWeeks, toPaddedString(1)),
'%WW': compose(_find.findWeeks, toPaddedString(2)),
'%D': compose(_find.findDays, toPaddedString(1)),
'%DD': compose(_find.findDays, toPaddedString(2)),
'%h': compose(_find.findHours, toPaddedString(1)),
'%hh': compose(_find.findHours, toPaddedString(2)),
'%m': compose(_find.findMinutes, toPaddedString(1)),
'%mm': compose(_find.findMinutes, toPaddedString(2)),
'%s': compose(_find.findSeconds, toPaddedString(1)),
'%ss': compose(_find.findSeconds, toPaddedString(2))
};
var SORTED_KEYS = Object.keys(TOKEN).sort(function (a, b) {
return b.length - a.length;
});
/**
* Formats a given iso duration by a given template.
*
* @param template {string} - the template including al placeholders
* @param isoString {string} - iso8601 duration string
* @example
* format('%hh:%mm:%ss', 'PT1M2S') // => '00:01:02'
*/
var format = (0, _utils.curry)(function (template, isoString) {
return SORTED_KEYS.reduce(function (result, key) {
return result.replace(new RegExp(key, 'g'), TOKEN[key](isoString));
}, template);
});
exports.format = format;