Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 58 additions & 1 deletion packages/cli-kit/src/public/common/array.test.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
14 changes: 7 additions & 7 deletions packages/cli-kit/src/public/common/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,13 @@ export function asHumanFriendlyArray<T>(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]
})
}
Loading