@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.
39 lines (37 loc) • 1.86 kB
JavaScript
import { isObject, isOptionsArgument } from "../../internal/isObject.js";
import { parseUnixEpochValue } from "../../internal/unixEpochValue.js";
// src/unix/validate/isValidUnixRange.ts
/**
* Return true if `value1` and `value2` form a valid Unix range — both safe-integer epochs
* and `value1 < value2` (or `<=` with `allowEqual`).
*
* - Each input must be a safe integer (`Number.isSafeInteger`) or a string of optionally negative
* ASCII digits naming one — the epoch grammar every `unix/` function shares.
* - Fractional values, `NaN`, `±Infinity` and anything beyond ±(2^53 − 1) return `false`.
* - Strings with whitespace, `+`, a decimal point, an exponent or hex digits return `false`, and an
* empty string is not epoch 0.
*
* @param props the two epoch values and the settings for the check
* @returns boolean indicating whether the Unix range is valid
*
* @example isValidUnixRange({ value1: 0, value2: 1700000000 }) // true
* @example isValidUnixRange({ value1: 1000, value2: 1000, options: { allowEqual: true } }) // true
* @example isValidUnixRange({ value1: 1700000000, value2: 0 }) // false (reversed)
* @example isValidUnixRange({ value1: 0, value2: 1.5 }) // false (fractional)
* @example isValidUnixRange({ value1: "", value2: 1000 }) // false (empty string is not epoch 0)
* @example isValidUnixRange({ value1: "0", value2: "1e3" }) // false (exponent notation is not an epoch)
*/
function isValidUnixRange(props) {
try {
if (!isObject(props)) return false;
const { value1, value2, options } = props;
if (!isOptionsArgument(options)) return false;
const first = parseUnixEpochValue(value1);
const second = parseUnixEpochValue(value2);
if (first === null || second === null) return false;
return options?.allowEqual ? first <= second : first < second;
} catch {
return false;
}
}
export { isValidUnixRange };