UNPKG

@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.

44 lines (42 loc) • 1.74 kB
import { Temporal } from "../../internal/temporal.js"; import { booleanOption } from "../../internal/typedOptions.js"; import { plainTimeOf } from "../../internal/inputChecks.js"; import { isObject, isOptionsArgument } from "../../internal/isObject.js"; // src/plain/validate/isValidTimeRange.ts /** * Return true if `value1` and `value2` form a valid time range — both parseable as * ISO PlainTime strings and `value1` before `value2`. * * - Both inputs must be ISO 8601 time strings (e.g. `"14:30:00"`), as `isValidTime` accepts, * annotations included. * - Ordered by `Temporal.PlainTime.compare`, to the nanosecond. * - Invalid input, malformed strings, or leap-second strings return `false`. * * @param props The two values to compare and how equal values are treated * @returns boolean indicating whether the time range is valid * * @example isValidTimeRange({ value1: "09:00:00", value2: "17:00:00" }) // true * @example isValidTimeRange({ value1: "17:00:00", value2: "09:00:00" }) // false * @example isValidTimeRange({ value1: "12:00:00", value2: "12:00:00", options: { allowEqual: true } }) // true */ function isValidTimeRange(props) { try { if (!isObject(props)) return false; const { value1, value2, options } = props; if (!isOptionsArgument(options)) return false; if (typeof value1 !== "string" || typeof value2 !== "string") return false; const time1 = plainTimeOf(value1); const time2 = plainTimeOf(value2); if (time1 === null || time2 === null) return false; try { const cmp = Temporal.PlainTime.compare(time1, time2); if (booleanOption(options?.allowEqual, false)) return cmp <= 0; return cmp < 0; } catch { return false; } } catch { return false; } } export { isValidTimeRange };