diff --git a/README.md b/README.md index 4a5d38d..8e25760 100644 --- a/README.md +++ b/README.md @@ -123,6 +123,8 @@ A collection of useful utility functions with associated TypeScript types. - [Dictionary](#dictionary) - [Constants](#constants) - [isJsdom](#isjsdom) + - [Arrays](#arrays) + - [toArray](#toarray) - [Attribution](#attribution) ## Install @@ -2435,6 +2437,32 @@ if (isJsdom) { --- +### Arrays + +--- + +#### toArray + +Checks the provided value is an array and if not returns the value within an array. + +| Parameter | Type | Optional | Description | +| --------- | ---- | -------- | -------------------- | +| value | any | false | The value to convert | + +Return type: `Array` + +**Example:** + +```typescript +import { toArray } from '@qntm-code/utils'; + +const array: Array = toArray('hello'); + +console.log(array); // ['hello'] +``` + +--- + ## Attribution - [isArguments](#isarguments), [isBuffer](#isbuffer), [isError](#iserror), [isGeneratorObject](#isgeneratorobject), [isRegExp](#isregexp), [typeOf](#typeof) initially based off Jon Schlinkert's [kind-of](https://github.com/jonschlinkert/kind-of) diff --git a/src/array/index.ts b/src/array/index.ts new file mode 100644 index 0000000..f05ba46 --- /dev/null +++ b/src/array/index.ts @@ -0,0 +1 @@ +export * from './to-array.js'; diff --git a/src/array/to-array.spec.ts b/src/array/to-array.spec.ts new file mode 100644 index 0000000..6541fe9 --- /dev/null +++ b/src/array/to-array.spec.ts @@ -0,0 +1,15 @@ +import { toArray } from './to-array'; + +describe('toArray', () => { + it('should return the provided value if it is already an array', () => { + const value = ['a', 'b']; + + expect(toArray(value)).toBe(value); + }); + + it('should return the provided value in a new array if it is not already an array', () => { + const value = 'a'; + + expect(toArray(value)).toEqual([value]); + }); +}); diff --git a/src/array/to-array.ts b/src/array/to-array.ts new file mode 100644 index 0000000..066a851 --- /dev/null +++ b/src/array/to-array.ts @@ -0,0 +1,6 @@ +/** + * Checks the provided value is an array and if not returns the value within an array. + */ +export function toArray(value: T | T[]): T[] { + return Array.isArray(value) ? value : [value]; +} diff --git a/src/index.ts b/src/index.ts index 54349a9..4ef078b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,4 @@ +export * from './array/index.js'; export * from './async/index.js'; export * from './clone/clone.js'; export * from './constants/index.js';