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.

40 lines (38 loc) • 1.37 kB
import { Temporal } from "../../internal/temporal.js"; import { plainDateTimeOf } from "../../internal/inputChecks.js"; // src/plain/calculate/sortDateTimes.ts /** * Sort an array of PlainDateTime values in ascending or descending order. * * - Returns empty array if no valid datetimes. * - Validation is performed on each item in the array. * * @param dateTimes Array of ISO PlainDateTime strings (e.g. "2024-03-10T12:00:00") * @param order "asc" for ascending (earliest first) | "desc" for descending (latest first) * @returns Sorted array of datetime strings * * @example sortDateTimes(["2024-03-10T12:00:00", "2024-01-01T08:00:00", "2024-02-15T15:30:00"]) // ["2024-01-01T08:00:00", "2024-02-15T15:30:00", "2024-03-10T12:00:00"] * @example sortDateTimes([]) // [] */ function sortDateTimes(dateTimes, order = "asc") { try { if (!Array.isArray(dateTimes) || !dateTimes.length) return []; const valid = []; dateTimes.forEach((item) => { const parsed = plainDateTimeOf(item); if (parsed !== null) valid.push(parsed); }); if (!valid.length) return []; try { const comparables = valid; comparables.sort(Temporal.PlainDateTime.compare); if (order === "desc") return comparables.reverse().map((d) => d.toString()); return comparables.map((d) => d.toString()); } catch { return []; } } catch { return []; } } export { sortDateTimes };