toSafeInteger
lang
Converts value to a safe integer.
Installation
Import
import { toSafeInteger } from '@tulx/utils';Source Code
Implementation
/**
* Converts value to a safe integer.
*
* @param value - The value to convert.
* @returns Returns the converted integer.
*
* @example
* ```ts
* toSafeInteger(3.2); // 3
* toSafeInteger(Number.MIN_VALUE); // 0
* toSafeInteger(Infinity); // 9007199254740991
* toSafeInteger('3.2'); // 3
* ```
*/
export function toSafeInteger(value: unknown): number {
const num = Number(value);
if (!Number.isFinite(num)) {
return num > 0 ? Number.MAX_SAFE_INTEGER : Number.MIN_SAFE_INTEGER;
}
return Math.trunc(
Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)
);
}
Example
import { toSafeInteger } from '@tulx/utils';
toSafeInteger(3.2); // 3
toSafeInteger(Number.MIN_VALUE); // 0
toSafeInteger(Infinity); // 9007199254740991
toSafeInteger('3.2'); // 3Related Functions
castArray
Casts value as an array if it's not one.
clone
Creates a shallow clone of value.
cloneDeep
This method is like clone except that it recursively clones value.
cloneDeepWith
This method is like cloneDeep except that it accepts customizer which is invoked to produce the cloned value.
cloneWith
This method is like clone except that it accepts customizer which is invoked to produce the cloned value.
conformsTo
Checks if object conforms to source by invoking the predicate properties of source with the corresponding property values of object.