@nexim/sanitizer
Version:
A collection of sanitization utilities for phone numbers and numeric inputs with TypeScript type safety.
48 lines • 1.44 kB
JavaScript
/**
* Checks if a value is a finite number
* Handles NaN properly and provides polyfill for old environments
*/
function isFiniteNumber(value) {
if (typeof Number.isFinite === 'function') {
return Number.isFinite(value);
}
return typeof value === 'number' && isFinite(value);
}
/**
* Checks if a value is a valid number
* Handles: number type, string conversion, empty strings
* Uses NaN check: value - value === 0 (only true for valid numbers)
*/
export function isNumber(value) {
if (typeof value === 'number') {
// NaN check: NaN - NaN = NaN, others return 0
return value - value === 0;
}
if (typeof value === 'string') {
const trimmed = value.trim();
if (trimmed === '')
return false;
const num = +trimmed;
return isFiniteNumber(num);
}
return false;
}
/**
* Converts a value to a number or returns null if invalid
* Handles: number type, string conversion, preserves valid numbers
*/
export function toNumber(value) {
if (typeof value === 'number') {
// Return number only if it's not NaN
return value - value === 0 ? value : null;
}
if (typeof value === 'string') {
const trimmed = value.trim();
if (trimmed === '')
return null;
const num = +trimmed;
return isFiniteNumber(num) ? num : null;
}
return null;
}
//# sourceMappingURL=utils.js.map