Skip to content

Commit

Permalink
Add lastOrDefault function to array.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
shtse8 committed Mar 22, 2024
1 parent 0e1f447 commit 0707723
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@ export function last<T>(arr: T[]): T {
return arr[arr.length - 1];
}

/**
* Returns the last element of an array, or a default value if the array is empty.
* @param arr array to get the last element from
* @param defaultValue default value
* @returns the last element of the array, or the default value if the array is empty
*/
export function lastOrDefault<T, D>(arr: T[], defaultValue: D): T | D {
return arr.length > 0 ? arr[arr.length - 1] : defaultValue;
}

/**
* Returns the first element of an array
* @param arr array to get the first element from
Expand Down Expand Up @@ -232,6 +242,6 @@ export function flatMap<T, U>(arr: T[], fn: (x: T) => U[]): U[] {
* firstOrDefault([1, 2, 3], 0) // returns 1
* firstOrDefault([], 0) // returns 0
*/
export function firstOrDefault<T>(arr: T[], defaultValue: T): T {
export function firstOrDefault<T, D>(arr: T[], defaultValue: D): T | D {
return arr.length > 0 ? arr[0] : defaultValue
}

0 comments on commit 0707723

Please sign in to comment.