UNPKG

@everwhen/temporal

Version:
143 lines 4.11 kB
import { Duration } from './duration.js'; import { isPlainTime } from './is.js'; export class Sequence { constructor(start, end, step) { Object.defineProperty(this, "start", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "end", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "step", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "total", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.start = start; this.end = end; this.step = Duration.from(step); this.total = this.start.until(this.end); } static from(bounds) { const stepDefault = {}; if (isPlainTime(bounds.start)) { stepDefault.hours = 1; } else { stepDefault.days = 1; } return new Sequence(bounds.start, bounds.end, bounds.step ?? stepDefault); } *[Symbol.iterator]() { let current = this.start; let accumulated = Duration.from('PT0S'); const opts = {}; if (!isPlainTime(this.start)) { opts.relativeTo = this.start; } yield current; while (current.compare(this.end) < 0) { accumulated = accumulated.add(this.step); if (accumulated.compare(this.total) > 0) { break; } current = current.add(this.step); yield current; } } get bounds() { return { start: this.start, end: this.end }; } *items() { let accumulated = Duration.from('PT0S'); const item = { value: this.start, next: this.start.add(this.step), }; const opts = {}; if (!isPlainTime(this.start)) { opts.relativeTo = this.start; } yield item; while (item.value.compare(this.end) < 0) { accumulated = accumulated.add(this.step); if (accumulated.compare(this.total, opts) > 0) { break; } item.previous = item.value; item.value = item.value.add(this.step); const nextAccumulated = accumulated.add(this.step); if (nextAccumulated.compare(this.total, opts) <= 0) { item.next = item.value.add(this.step); } else { delete item.next; } yield item; } } forEach(callbackfn) { let index = 0; for (const val of this) { callbackfn(val, index); index += 1; } } map(mapper) { const items = []; for (const tem of this) { items.push(mapper(tem)); } return items; } group(keyFn) { const groups = new Map(); for (const item of this) { const key = keyFn(item); if (!groups.has(key)) { groups.set(key, []); } groups.get(key).push(item); } return groups; } select(predicate, mapper) { const values = []; for (const item of this) { if (predicate(item)) { values.push(mapper(item)); } } return values; } filter(predicate) { return this.select(predicate, (t) => t); } with(bounds) { return new Sequence(bounds.start ?? this.start, bounds.end ?? this.end, bounds.step ?? this.step); } get length() { return Array.from(this).length; } toJSON() { return { start: this.start.toString(), end: this.end.toString(), step: this.step.toString(), }; } } //# sourceMappingURL=sequence.js.map