diff --git a/packages/cli-kit/src/public/common/array.test.ts b/packages/cli-kit/src/public/common/array.test.ts index 720becbac0b..16a1b86f8bd 100644 --- a/packages/cli-kit/src/public/common/array.test.ts +++ b/packages/cli-kit/src/public/common/array.test.ts @@ -1,6 +1,63 @@ -import {difference, uniq, uniqBy} from './array.js' +import {asHumanFriendlyArray, difference, uniq, uniqBy} from './array.js' import {describe, test, expect} from 'vitest' +describe('asHumanFriendlyArray', () => { + test('returns an empty array when given an empty array', () => { + // Given + const items: string[] = [] + + // When + const got = asHumanFriendlyArray(items) + + // Then + expect(got).toEqual([]) + }) + + test('returns the same array when it has one item', () => { + // Given + const items = ['apple'] + + // When + const got = asHumanFriendlyArray(items) + + // Then + expect(got).toEqual(['apple']) + }) + + test('returns the items separated by and when it has two items', () => { + // Given + const items = ['apple', 'banana'] + + // When + const got = asHumanFriendlyArray(items) + + // Then + expect(got).toEqual(['apple', 'and', 'banana']) + }) + + test('returns the items separated by commas and and when it has more than two items', () => { + // Given + const items = ['apple', 'banana', 'orange'] + + // When + const got = asHumanFriendlyArray(items) + + // Then + expect(got).toEqual(['apple', ', ', 'banana', 'and', 'orange']) + }) + + test('works with objects', () => { + // Given + const items = ['apple', 'banana', {command: '--flag'}] + + // When + const got = asHumanFriendlyArray(items) + + // Then + expect(got).toEqual(['apple', ', ', 'banana', 'and', {command: '--flag'}]) + }) +}) + describe('uniqBy', () => { test('removes duplicates', () => { // When 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] + }) }