Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding isNonEmptyArray #309

Merged
merged 2 commits into from
Aug 28, 2024
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest'
import { isNonEmptyArray } from './isNonEmptyArray'

describe('arrayUtils', () => {
describe('isNonEmptyArray', () => {
it('returns false if array is empty ', () => {
expect(isNonEmptyArray([])).toBe(false)
})

it('returns true if array is not empty', () => {
expect(isNonEmptyArray(['hello', 'world'])).toBe(true)
})

it('type guard works', () => {
const array = [1, 2, 3]
if (!isNonEmptyArray(array)) throw new Error('Array should not be empty')

// Ensure the type is inferred correctly at compile-time
type Assert<T, Expected> = T extends Expected ? true : false
type Check = Assert<typeof array, [number, ...number[]]>
const isCorrectType: Check = true // If this line fails, type guard is not working
expect(isCorrectType).toBe(true)
})
})
})
12 changes: 12 additions & 0 deletions packages/app/universal-ts-utils/src/array/isNonEmptyArray.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Checks if the given array is non-empty.
*
* This function is a type guard that not only checks whether the array has at least one element,
* but also refines the type of the array to be a tuple indicating that the first element exists.
* This is useful for preventing operations on empty arrays and for gaining type-level assurances.
*
* @template T - The type of elements within the array.
* @param {T[]} array - The array to be checked, which should be read-only.
* @returns {array is [T, ...T[]]} - Returns true if the array is non-empty, false otherwise.
*/
export const isNonEmptyArray = <T>(array: T[]): array is [T, ...T[]] => array.length > 0
Loading