From 4d9373e9129357833938ad61bb85de30d4d4d1a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Levi=20=28Nguy=E1=BB=85n=20L=C6=B0=C6=A1ng=20Huy=29?= Date: Tue, 1 Nov 2022 03:11:44 +0700 Subject: [PATCH] fix(array): `toArray` - convert to empty array only for nullish (#20) --- src/array.test.ts | 19 +++++++++++++++++-- src/array.ts | 6 ++---- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/array.test.ts b/src/array.test.ts index 4308d81..c569b38 100644 --- a/src/array.test.ts +++ b/src/array.test.ts @@ -1,5 +1,20 @@ -import { expect, it } from 'vitest' -import { flattenArrayable, partition, range } from './array' +import { describe, expect, it } from 'vitest' +import { flattenArrayable, partition, range, toArray } from './array' + +describe('toArray', () => { + it.each([ + [undefined, []], + [null, []], + [false, [false]], + [0, [0]], + ['', ['']], + [[], []], + ['foo', ['foo']], + [['foo'], ['foo']], + ])('%s => %s', (input, expected) => { + expect(toArray(input)).toEqual(expected) + }) +}) it('flattenArrayable', () => { expect(flattenArrayable()).toEqual([]) diff --git a/src/array.ts b/src/array.ts index cbd215c..173bfc8 100644 --- a/src/array.ts +++ b/src/array.ts @@ -7,10 +7,8 @@ import type { Arrayable, Nullable } from './types' * @category Array */ export function toArray(array?: Nullable>): Array { - array = array || [] - if (Array.isArray(array)) - return array - return [array] + array = array ?? [] + return Array.isArray(array) ? array : [array] } /**