@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.1 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { isValidDate } from "../validate/isValidDate.js";
// src/plain/calculate/maxDate.ts
/**
* Return the latest (maximum) of the given PlainDate values.
*
* - Returns null if the array is empty or contains no valid dates.
* - Validation is performed on each item in the array.
*
* @param dates Array of ISO PlainDate strings (e.g. "2024-03-10")
* @returns The latest date string, or null on invalid input
*
* @example maxDate(["2024-03-10", "2024-03-15", "2024-03-12"]) // "2024-03-15"
* @example maxDate([]) // null
*/
function maxDate(dates) {
try {
if (!Array.isArray(dates) || !dates.length) return null;
const valid = dates.filter(isValidDate);
if (!valid.length) return null;
try {
return valid.reduce((currentMax, candidateStr) => {
const candidate = Temporal.PlainDate.from(candidateStr);
return Temporal.PlainDate.compare(candidate, currentMax) > 0 ? candidate : currentMax;
}, Temporal.PlainDate.from(valid[0])).toString();
} catch {
return null;
}
} catch {
return null;
}
}
export { maxDate };