UNPKG

compare-shield

Version:

A coercion-free numeric comparison utility for <, <=, >, >= within JavaScript's safe integer range.

70 lines (69 loc) 2.15 kB
// Constant for valid operators const VALID_OPERATORS = ["<", "<=", ">", ">="]; /** * Executes a strict numeric comparison without implicit type conversion. * Ensures that both operands are valid finite numbers. * Returns false for invalid inputs, unsupported operators, or special numeric values. * * @param a - First operand to compare * @param operator - Comparison operator: '<', '<=', '>', '>=' * @param b - Second operand to compare * @returns True if both operands are valid and the comparison succeeds; false otherwise * * @example * import { compare } from 'compare-shield'; * * compare(5, '<', 10); // true * compare(3.14, '<=', 3.14); // true * compare(null, '<', 5); // false * compare(NaN, '>=', 0); // false * compare(Infinity, '<', 1000); // false */ export function compare(a, operator, b) { const isValidOperator = VALID_OPERATORS.includes(operator); // Check operator validity if (!isValidOperator) { return false; } // Extract validation checks to variables const isANullish = a === null || a === undefined; const isBNullish = b === null || b === undefined; // Check for null/undefined if (isANullish || isBNullish) { return false; } const isANumber = typeof a === "number"; const isBNumber = typeof b === "number"; const isAFinite = isANumber && Number.isFinite(a); const isBFinite = isBNumber && Number.isFinite(b); const isASafeInteger = Number.isSafeInteger(a); const isBSafeInteger = Number.isSafeInteger(b); // Check types, finite values and if values are safe to perform comparison on if (!isANumber || !isBNumber || !isAFinite || !isBFinite || !isASafeInteger || !isBSafeInteger) { return false; } // Perform the comparison switch (operator) { case "<": { return a < b; } case "<=": { return a <= b; } case ">": { return a > b; } case ">=": { return a >= b; } default: { return false; } } } export default compare;