Skip to content

Commit

Permalink
feat: improve function arrLast
Browse files Browse the repository at this point in the history
  • Loading branch information
GreatAuk committed May 9, 2024
1 parent 2a4e517 commit 13af4ad
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 3 deletions.
1 change: 1 addition & 0 deletions packages/core/src/arrLast.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ describe('arrLast', () => {
expect(arrLast(['a', 1, true, /r/g])).toEqual(/r/g)
expect(arrLast([1])).toBe(1)
expect(arrLast([])).toBe(undefined)
expect(arrLast<string[]>([], 'he')).toBe('he')
})
it('should work with readonly arrays', () => {
const arr = [1, 2, 3, 4, 5] as const
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/arrLast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ type ArrayLast<T extends readonly unknown[]> = T extends readonly [...infer _, i
* ```
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/arrLast.ts
*/
export function arrLast<T extends readonly unknown[]>(arr: T): ArrayLast<T>
export function arrLast<T extends unknown[]>(arr: T): T[number] {
export function arrLast<T extends readonly unknown[]>(arr: T, defaultValue?: T[number] | null | undefined): ArrayLast<T>
export function arrLast<T extends unknown[]>(arr: T, defaultValue?: T[number] | null | undefined): T[number] {
if (!Array.isArray(arr))
throw new TypeError('Expected an Array')
return arr[arr.length - 1]
return arr?.length > 0 ? arr[arr.length - 1] : defaultValue
}
2 changes: 2 additions & 0 deletions packages/core/src/capitalize.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ import { capitalize } from './capitalize'
describe('capitalize', () => {
it('should capitalize the first letter of a string', () => {
expect(capitalize('foo')).toBe('Foo')
expect(capitalize('hello world')).toBe('Hello world')
expect(capitalize('')).toBe('')
})
})

0 comments on commit 13af4ad

Please sign in to comment.