UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

90 lines (89 loc) 2.24 kB
import { localTime } from './localTime.js'; /** * Class that supports an "interval of time" between 2 timestamps - start and end. * Example: `1649267185/1649267187`. * * @experimental */ export class TimeInterval { $start; $end; constructor($start, $end) { this.$start = $start; this.$end = $end; } static of(start, end) { return new TimeInterval(localTime.fromInput(start).unix, localTime.fromInput(end).unix); } get start() { return this.$start; } get end() { return this.$end; } get startTime() { return localTime(this.$start); } get endTime() { return 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) { d = localTime.fromInput(d).unix; if (d < this.$start) return false; if (d > this.$end) 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(); } }