size
collection
Gets the size of collection by returning its length for array-like values or the number of own enumerable string keyed properties for objects.
Installation
Import
import { size } from '@tulx/utils';Source Code
Implementation
/**
* Gets the size of collection by returning its length for array-like values or the number of own enumerable string keyed properties for objects.
*
* @param collection - The collection to inspect.
* @returns Returns the collection size.
*
* @example
* ```ts
* size([1, 2, 3]); // 3
* size({ 'a': 1, 'b': 2 }); // 2
* size('pebbles'); // 7
* ```
*/
export function size(
collection: readonly unknown[] | Record<string, unknown> | string
): number {
if (typeof collection === 'string' || Array.isArray(collection)) {
return collection.length;
}
let count = 0;
for (const key in collection) {
if (Object.prototype.hasOwnProperty.call(collection, key)) {
count++;
}
}
return count;
}
Example
import { size } from '@tulx/utils';
size([1, 2, 3]); // 3
size({ 'a': 1, 'b': 2 }); // 2
size('pebbles'); // 7Related Functions
countBy
Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The corresponding value of each key is the number of times the key was returned by iteratee.
each
Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection).
eachRight
This method is like each except that it iterates over elements of collection from right to left.
every
Checks if predicate returns truthy for all elements of collection.
filter
Iterates over elements of collection, returning an array of all elements predicate returns truthy for.
find
Iterates over elements of collection, returning the first element predicate returns truthy for.