UNPKG

@northguild/gmt

Version:

Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.

38 lines (36 loc) • 1.64 kB
import { Temporal } from "../../internal/temporal.js"; import { utcInstantOf } from "../../internal/utcInstant.js"; // src/utc/calculate/sortUtc.ts /** * Sort an array of UTC datetime values in ascending or descending order. * * - Filters invalid values before sorting. * - Supports "asc" (earliest first) or "desc" (latest first). * - Returns [] if array is empty or has no valid values. * * @param utcDateTimes Array of ISO datetime strings (e.g. "2024-03-10T12:00:00Z") * @param order "asc" for ascending (earliest first) | "desc" for descending (latest first) * @returns Sorted array of UTC datetime strings * * @example sortUtc(["2024-03-12T12:00:00Z", "2024-03-10T12:00:00Z", "2024-03-15T12:00:00Z"]) // ["2024-03-10T12:00:00Z", "2024-03-12T12:00:00Z", "2024-03-15T12:00:00Z"] * @example sortUtc(["2024-03-12T12:00:00Z", "2024-03-10T12:00:00Z", "2024-03-15T12:00:00Z"], "desc") // ["2024-03-15T12:00:00Z", "2024-03-12T12:00:00Z", "2024-03-10T12:00:00Z"] * @example sortUtc(["invalid", "2024-03-10T12:00:00Z", "also invalid"]) // ["2024-03-10T12:00:00Z"] * @example sortUtc([]) // [] */ function sortUtc(utcDateTimes, order = "asc") { try { if (!Array.isArray(utcDateTimes) || !utcDateTimes.length) return []; const comparables = utcDateTimes.map((candidate) => utcInstantOf(candidate)).filter((candidate) => candidate !== null); if (!comparables.length) return []; try { comparables.sort(Temporal.Instant.compare); if (order === "desc") return comparables.reverse().map((d) => d.toString()); return comparables.map((d) => d.toString()); } catch { return []; } } catch { return []; } } export { sortUtc };