diff --git a/packages/cli-kit/src/public/common/array.test.ts b/packages/cli-kit/src/public/common/array.test.ts index 720becbac0b..4a868ce582c 100644 --- a/packages/cli-kit/src/public/common/array.test.ts +++ b/packages/cli-kit/src/public/common/array.test.ts @@ -1,4 +1,4 @@ -import {difference, uniq, uniqBy} from './array.js' +import {asHumanFriendlyArray, difference, uniq, uniqBy} from './array.js' import {describe, test, expect} from 'vitest' describe('uniqBy', () => { @@ -62,3 +62,38 @@ describe('difference', () => { expect(got).toEqual([1]) }) }) + +describe('asHumanFriendlyArray', () => { + test('returns the same array if it has less than 2 elements', () => { + // Given + const array = ['apple'] + + // When + const got = asHumanFriendlyArray(array) + + // Then + expect(got).toEqual(['apple']) + }) + + test('returns a human friendly array if it has 2 elements', () => { + // Given + const array = ['apple', 'banana'] + + // When + const got = asHumanFriendlyArray(array) + + // Then + expect(got).toEqual(['apple', 'and', 'banana']) + }) + + test('returns a human friendly array if it has more than 2 elements', () => { + // Given + const array = ['apple', 'banana', 'orange'] + + // When + const got = asHumanFriendlyArray(array) + + // Then + expect(got).toEqual(['apple', ', ', 'banana', 'and', 'orange']) + }) +}) diff --git a/packages/cli-kit/src/public/common/array.ts b/packages/cli-kit/src/public/common/array.ts index 8b22c0b7b93..5dc1934b558 100644 --- a/packages/cli-kit/src/public/common/array.ts +++ b/packages/cli-kit/src/public/common/array.ts @@ -90,13 +90,13 @@ export function asHumanFriendlyArray(items: T[]): (T | string)[] { return items } - return items.reduce<(T | string)[]>((acc, item, index) => { + return items.flatMap((item, index) => { + if (index === 0) { + return [item] + } if (index === items.length - 1) { - acc.push('and') - } else if (index !== 0) { - acc.push(', ') + return ['and', item] } - acc.push(item) - return acc - }, []) + return [', ', item] + }) }