Add getMiddleElement array util

This commit is contained in:
2024-12-05 11:15:51 +01:00
parent 7af53bbec0
commit 6efea94dd0
2 changed files with 30 additions and 1 deletions
+17
View File
@@ -73,3 +73,20 @@ export function groupBy<E, K>(
[] as { key: K; elements: Array<E> }[]
);
}
/**
* Return the middle Element of an array, rounding up.
* Returns undefined for empty arrays without throwing!
*
* @example
* ```typescript
* getMiddleElement([1, 2, 3, 4]) === 3
* getMiddleElement([1, 2, 3]) === 2
* getMiddleElement([1]) === 1
* getMiddleElement([]) === undefined
* ```
* @param arr
*/
export function getMiddleElement<E>(arr: ReadonlyArray<E>) {
return arr[Math.floor(arr.length / 2)];
}