Skip to content
Closed
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
Empty file added .jules/bolt.md
Empty file.
37 changes: 36 additions & 1 deletion packages/cli-kit/src/public/common/array.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {difference, uniq, uniqBy} from './array.js'
import {difference, getArrayContainsDuplicates, uniq, uniqBy} from './array.js'
import {describe, test, expect} from 'vitest'

describe('uniqBy', () => {
Expand Down Expand Up @@ -62,3 +62,38 @@ describe('difference', () => {
expect(got).toEqual([1])
})
})

describe('getArrayContainsDuplicates', () => {
test('returns true if the array contains duplicates', () => {
// Given
const array = [1, 2, 2, 3]

// When
const got = getArrayContainsDuplicates(array)

// Then
expect(got).toBe(true)
})

test('returns false if the array does not contain duplicates', () => {
// Given
const array = [1, 2, 3]

// When
const got = getArrayContainsDuplicates(array)

// Then
expect(got).toBe(false)
})

test('returns false for an empty array', () => {
// Given
const array: number[] = []

// When
const got = getArrayContainsDuplicates(array)

// Then
expect(got).toBe(false)
})
})
13 changes: 12 additions & 1 deletion packages/cli-kit/src/public/common/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,22 @@ export function getArrayRejectingUndefined<T>(array: (T | undefined)[]): T[] {
/**
* Returns true if an array contains duplicates.
*
* This implementation is optimized to exit early as soon as the first duplicate
* is found, avoiding unnecessary processing of the rest of the array.
* Time complexity: O(k) where k is the index of the first duplicate, O(n) otherwise.
*
* @param array - The array to check against.
* @returns True if the array contains duplicates.
*/
export function getArrayContainsDuplicates<T>(array: T[]): boolean {
return array.length !== new Set(array).size
const seen = new Set<T>()
for (const item of array) {
if (seen.has(item)) {
return true
}
seen.add(item)
}
return false
}

/**
Expand Down
Loading