From eed2889cdb1a084f57311aa9b36b6b18e52c2601 Mon Sep 17 00:00:00 2001 From: gonzaloriestra <14979109+gonzaloriestra@users.noreply.github.com> Date: Mon, 29 Jun 2026 00:30:33 +0000 Subject: [PATCH] refactor: use flatMap in asHumanFriendlyArray Replace the reduce implementation in asHumanFriendlyArray with a more declarative flatMap approach to improve readability. Added unit tests to verify behavior for edge cases and multi-element arrays. --- .../cli-kit/src/public/common/array.test.ts | 37 ++++++++++++++++++- packages/cli-kit/src/public/common/array.ts | 14 +++---- 2 files changed, 43 insertions(+), 8 deletions(-) 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] + }) }