@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.
35 lines (33 loc) • 1.09 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { isValidTime } from "../validate/isValidTime.js";
// src/plain/calculate/maxTime.ts
/**
* Return the latest (maximum) of the given PlainTime values.
*
* - Returns null if the array is empty or contains no valid times.
* - Validation is performed on each item in the array.
*
* @param times Array of ISO PlainTime strings (e.g. "14:30:00")
* @returns The latest time string, or null on invalid input
*
* @example maxTime(["14:30:00", "09:00:00", "20:45:00"]) // "20:45:00"
* @example maxTime([]) // null
*/
function maxTime(times) {
try {
if (!Array.isArray(times) || !times.length) return null;
const valid = times.filter(isValidTime);
if (!valid.length) return null;
try {
return valid.reduce((currentMax, candidateStr) => {
const candidate = Temporal.PlainTime.from(candidateStr);
return Temporal.PlainTime.compare(candidate, currentMax) > 0 ? candidate : currentMax;
}, Temporal.PlainTime.from(valid[0])).toString();
} catch {
return null;
}
} catch {
return null;
}
}
export { maxTime };