pomeranian-durations
Version:
An immutable duration library based on the ISO-8601 format for durations.
86 lines (74 loc) • 2.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sortDescBy = exports.sortDesc = exports.sortAscBy = exports.sortAsc = void 0;
var _constants = require("./constants");
var _transformations = require("./transformations");
var _utils = require("./_utils");
/**
* Helpers to sort durations. Attention durations with multiple date parts can only
* be compared using an approximation, so the result might be incorrect! (eg. on some
* days the following is true: 'PT23H1M' > 'PT1D'). If you're using the same units in
* all given durations that is not an issue.
* @name default
*/
var toApproximateSeconds = function toApproximateSeconds(isoDuration) {
var fragments = (0, _transformations.toFragments)(isoDuration);
return [fragments.seconds * _constants.ONE_SECOND, fragments.minutes * _constants.ONE_MINUTE, fragments.hours * _constants.ONE_HOUR, fragments.days * _constants.ONE_DAY, fragments.weeks * _constants.ONE_DAY * 7, fragments.months * _constants.ONE_DAY * 30, fragments.years * _constants.ONE_DAY * 364.25].reduce(function (sum, seconds) {
return sum + seconds;
}, 0);
};
var flipArguments = function flipArguments(fn) {
return function (a, b) {
return fn(b, a);
};
};
/**
* A function which can be used to sort durations ASC.
*
* @param a, {string} an ISO8601 duration
* @param b, {string} an ISO8601 duration
* @example
* ['PT2S', 'PT1S'].sort(sortAsc) // ['PT1S', 'PT2S']
*/
var sortAsc = function sortAsc(a, b) {
return toApproximateSeconds(a) - toApproximateSeconds(b);
};
/**
* A function which can be used to sort durations in an array of objects ASC.
*
* @param a, {string} an ISO8601 duration
* @param b, {string} an ISO8601 duration
* @example
* [{ randomKey: 'PT2S' }, { randomKey: 'PT1S' }].sort(sortAscBy('randomKey'))
* // => [{ randomKey: 'PT1S' }, { randomKey: 'PT2S' }]
*/
exports.sortAsc = sortAsc;
var sortAscBy = (0, _utils.curry)(function (key, a, b) {
return sortAsc(a[key], b[key]);
});
/**
* A function which can be used to sort durations DESC.
*
* @param a, {string} an ISO8601 duration
* @param b, {string} an ISO8601 duration
* @example
* ['PT1S', 'PT2S'].sort(sortDesc) // ['PT2S', 'PT1S']
*/
exports.sortAscBy = sortAscBy;
var sortDesc = flipArguments(sortAsc);
/**
* A function which can be used to sort durations in an array of objects DESC.
*
* @param a, {string} an ISO8601 duration
* @param b, {string} an ISO8601 duration
* @example
* [{ randomKey: 'PT2S' }, { randomKey: 'PT1S' }].sort(sortDescBy('randomKey'))
* // => [{ randomKey: 'PT2S' }, { randomKey: 'PT1S' }]
*/
exports.sortDesc = sortDesc;
var sortDescBy = (0, _utils.curry)(function (key, a, b) {
return sortDesc(a[key], b[key]);
});
exports.sortDescBy = sortDescBy;