import {type TimeZone as ZoneTimeZone} from '@clarify/zone'; const MINUTE = 1000 * 60; function binarySearch(nodes: (number | null)[], time: number, right: boolean = true) { let index = 0; let toIndex = nodes.length - 1; while (index !== toIndex) { let midIndex = Math.floor((index + toIndex) / 2); if (right && time < (nodes[midIndex] ?? Infinity)) { toIndex = midIndex; } else if (!right && time <= (nodes[midIndex] ?? Infinity)) { toIndex = midIndex; } else { index = index === midIndex ? toIndex : midIndex; } } return index; } export interface Zone { name: string; untils: (number | null)[]; offsets: number[]; } export interface TimeZonesPayload { timeZones: [string, Zone][]; aliases: [string, string]; } let timeZones = new Map(); export function populateTimeZones(payload: TimeZonesPayload) { timeZones = new Map(payload.timeZones); for (let [name, original] of payload.aliases) { let parent = timeZones.get(original); if (parent) { timeZones.set(name, parent); } } } export class PrecalculatedTimeZone implements ZoneTimeZone { constructor( public readonly id: string, public readonly untils: (number | null)[], public readonly offsets: number[], ) {} getOffsetMillisecondsFor(milliseconds: number): number { let transitionIndex = binarySearch(this.untils, milliseconds); return this.offsets[transitionIndex] * MINUTE * -1; } getTimeZoneTransition(milliseconds: number, direction: 'next' | 'previous'): number | null { let transitionIndex = binarySearch(this.untils, milliseconds, direction === 'next'); switch (direction) { case 'next': return this.untils[transitionIndex] ?? null; case 'previous': return this.untils[transitionIndex - 1] ?? null; } } static from(name: string) { let timeZone = timeZones.get(name); if (!timeZone) { throw new RangeError(`TimeZone ${name} not loaded`); } return new PrecalculatedTimeZone(timeZone.name, timeZone.untils, timeZone.offsets); } }