toArray
lang
Converts value to an array.
Installation
Import
import { toArray } from '@tulx/utils';Source Code
Implementation
/**
* Converts value to an array.
*
* @param value - The value to convert.
* @returns Returns the converted array.
*
* @example
* ```ts
* toArray({ 'a': 1, 'b': 2 }); // [1, 2]
* toArray('abc'); // ['a', 'b', 'c']
* toArray(1); // []
* toArray(null); // []
* ```
*/
export function toArray(value: unknown): unknown[] {
if (value === null || value === undefined) {
return [];
}
if (Array.isArray(value)) {
return [...value];
}
if (typeof value === 'string') {
return value.split('');
}
if (typeof value === 'object') {
return Object.values(value);
}
return [];
}
Example
import { toArray } from '@tulx/utils';
toArray({ 'a': 1, 'b': 2 }); // [1, 2]
toArray('abc'); // ['a', 'b', 'c']
toArray(1); // []
toArray(null); // []Related 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.