@naturalcycles/js-lib
Version:
Standard library for universal (browser + Node.js) javascript
95 lines (94 loc) • 2.63 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimeInterval = void 0;
const localTime_1 = require("./localTime");
/**
* Class that supports an "interval of time" between 2 timestamps - start and end.
* Example: `1649267185/1649267187`.
*
* @experimental
*/
class TimeInterval {
$start;
$end;
constructor($start, $end) {
this.$start = $start;
this.$end = $end;
}
static of(start, end) {
return new TimeInterval(localTime_1.localTime.fromInput(start).unix, localTime_1.localTime.fromInput(end).unix);
}
get start() {
return this.$start;
}
get end() {
return this.$end;
}
get startTime() {
return (0, localTime_1.localTime)(this.$start);
}
get endTime() {
return (0, localTime_1.localTime)(this.$end);
}
/**
* Parses string like `1649267185/1649267187` into a TimeInterval.
*/
static parse(d) {
if (d instanceof TimeInterval)
return d;
const [start, end] = d.split('/').map(Number);
if (!end || !start) {
throw new Error(`Cannot parse "${d}" into TimeInterval`);
}
return new TimeInterval(start, end);
}
isSame(d) {
return this.cmp(d) === 0;
}
isBefore(d, inclusive = false) {
const r = this.cmp(d);
return r === -1 || (r === 0 && inclusive);
}
isSameOrBefore(d) {
return this.cmp(d) <= 0;
}
isAfter(d, inclusive = false) {
const r = this.cmp(d);
return r === 1 || (r === 0 && inclusive);
}
isSameOrAfter(d) {
return this.cmp(d) >= 0;
}
includes(d, incl = '[)') {
d = localTime_1.localTime.fromInput(d).unix;
// eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
if (d < this.$start || (d === this.$start && incl[0] === '('))
return false;
if (d > this.$end || (d === this.$end && incl[1] === ')'))
return false;
return true;
}
/**
* TimeIntervals compare by start date.
* If it's the same - then by end date.
*/
cmp(d) {
d = TimeInterval.parse(d);
if (this.$start > d.$start)
return 1;
if (this.$start < d.$start)
return -1;
if (this.$end > d.$end)
return 1;
if (this.$end < d.$end)
return -1;
return 0;
}
toString() {
return [this.$start, this.$end].join('/');
}
toJSON() {
return this.toString();
}
}
exports.TimeInterval = TimeInterval;