@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.
36 lines (34 loc) • 1.29 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { utcInstantOf } from "../../internal/utcInstant.js";
// src/utc/calculate/maxUtc.ts
/**
* Return the latest (maximum) of the given UTC datetime values.
*
* - Filters invalid values before finding maximum.
* - Returns null if array is empty or has no valid values.
*
* @param utcDateTimes Array of ISO datetime strings (e.g. "2024-03-10T12:00:00Z")
* @returns The latest UTC datetime string, or null on invalid input
*
* @example maxUtc(["2024-03-10T12:00:00Z", "2024-03-15T12:00:00Z", "2024-03-12T12:00:00Z"]) // "2024-03-15T12:00:00Z"
* @example maxUtc(["invalid", "2024-03-15T12:00:00Z"]) // "2024-03-15T12:00:00Z"
* @example maxUtc(["invalid", "also invalid"]) // null
* @example maxUtc([]) // null
*/
function maxUtc(utcDateTimes) {
try {
if (!Array.isArray(utcDateTimes) || !utcDateTimes.length) return null;
const valid = utcDateTimes.map((candidate) => utcInstantOf(candidate)).filter((candidate) => candidate !== null);
if (!valid.length) return null;
try {
return valid.reduce((currentMax, candidate) => {
return Temporal.Instant.compare(candidate, currentMax) > 0 ? candidate : currentMax;
}, valid[0]).toString();
} catch {
return null;
}
} catch {
return null;
}
}
export { maxUtc };