@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.23 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { plainTimeOf } from "../../internal/inputChecks.js";
// src/plain/calculate/sortTimes.ts
/**
* Sort an array of PlainTime values in ascending or descending order.
*
* - Returns empty array if no valid times.
* - Validation is performed on each item in the array.
*
* @param times Array of ISO PlainTime strings (e.g. "14:30:00")
* @param order "asc" for ascending (earliest first) | "desc" for descending (latest first)
* @returns Sorted array of time strings
*
* @example sortTimes(["14:30:00", "09:00:00", "20:45:00"]) // ["09:00:00", "14:30:00", "20:45:00"]
* @example sortTimes([]) // []
*/
function sortTimes(times, order = "asc") {
try {
if (!Array.isArray(times) || !times.length) return [];
const valid = [];
times.forEach((item) => {
const parsed = plainTimeOf(item);
if (parsed !== null) valid.push(parsed);
});
if (!valid.length) return [];
try {
const comparables = valid;
comparables.sort(Temporal.PlainTime.compare);
if (order === "desc") return comparables.reverse().map((t) => t.toString());
return comparables.map((t) => t.toString());
} catch {
return [];
}
} catch {
return [];
}
}
export { sortTimes };