getMinMax.tsx 773 B

1234567891011121314151617181920212223
  1. /**
  2. * Calculate min/max of an array simultaneously.
  3. * This prevents two things:
  4. * - Avoid extra allocations and iterations, just loop through once.
  5. * - Avoid `Maximum call stack size exceeded` when the array is too large
  6. * `Math.min()` & `Math.max()` will throw after about ~10⁷ which is A LOT of items.
  7. * See: https://stackoverflow.com/a/52613386
  8. *
  9. * `lodash.min()` & `lodash.max()` are also options, they use a while-loop as here,
  10. * but that also includes a comparator function which adds overhead.
  11. */
  12. export default function getMinMax(arr: number[]) {
  13. let len = arr.length;
  14. let min = Infinity;
  15. let max = -Infinity;
  16. while (len--) {
  17. min = arr[len] < min ? arr[len] : min;
  18. max = arr[len] > max ? arr[len] : max;
  19. }
  20. return {min, max};
  21. }