toLength
lang
Converts value to an integer suitable for use as the length of an array-like object.
Installation
Import
import { toLength } from '@tulx/utils';Source Code
Implementation
/**
* Converts value to an integer suitable for use as the length of an array-like object.
*
* @param value - The value to convert.
* @returns Returns the converted integer.
*
* @example
* ```ts
* toLength(3.2); // 3
* toLength(Number.MIN_VALUE); // 0
* toLength(Infinity); // 4294967295
* toLength('3.2'); // 3
* ```
*/
export function toLength(value: unknown): number {
const num = toInteger(value);
if (num < 0) {
return 0;
}
return Math.min(num, 4294967295);
}
function toInteger(value: unknown): number {
const num = Number(value);
if (!Number.isFinite(num) || num === 0) {
return 0;
}
return Math.trunc(num);
}
Example
import { toLength } from '@tulx/utils';
toLength(3.2); // 3
toLength(Number.MIN_VALUE); // 0
toLength(Infinity); // 4294967295
toLength('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.