@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.
38 lines (36 loc) • 1.11 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { plainDateOf } from "../../internal/inputChecks.js";
// src/plain/calculate/minDate.ts
/**
* Return the earliest (minimum) 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 earliest date string, or null on invalid input
*
* @example minDate(["2024-03-10", "2024-03-15", "2024-03-12"]) // "2024-03-10"
* @example minDate([]) // null
*/
function minDate(dates) {
try {
if (!Array.isArray(dates) || !dates.length) return null;
const valid = [];
dates.forEach((item) => {
const parsed = plainDateOf(item);
if (parsed !== null) valid.push(parsed);
});
if (!valid.length) return null;
try {
return valid.reduce((currentMin, candidate) => {
return Temporal.PlainDate.compare(candidate, currentMin) < 0 ? candidate : currentMin;
}, valid[0]).toString();
} catch {
return null;
}
} catch {
return null;
}
}
export { minDate };