array.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { NumberArray } from './type-helpers';
  7. // TODO move to mol-math as Vector???
  8. /** Get the maximum value in an array */
  9. export function arrayMax(array: ArrayLike<number>) {
  10. let max = -Infinity
  11. for (let i = 0, il = array.length; i < il; ++i) {
  12. if (array[i] > max) max = array[i]
  13. }
  14. return max
  15. }
  16. /** Get the minimum value in an array */
  17. export function arrayMin(array: ArrayLike<number>) {
  18. let min = Infinity
  19. for (let i = 0, il = array.length; i < il; ++i) {
  20. if (array[i] < min) min = array[i]
  21. }
  22. return min
  23. }
  24. /** Get the sum of values in an array */
  25. export function arraySum(array: ArrayLike<number>, stride = 1, offset = 0) {
  26. const n = array.length
  27. let sum = 0
  28. for (let i = offset; i < n; i += stride) {
  29. sum += array[i]
  30. }
  31. return sum
  32. }
  33. /** Get the mean of values in an array */
  34. export function arrayMean(array: ArrayLike<number>, stride = 1, offset = 0) {
  35. return arraySum(array, stride, offset) / (array.length / stride)
  36. }
  37. /** Get the root mean square of values in an array */
  38. export function arrayRms(array: ArrayLike<number>) {
  39. const n = array.length
  40. let sumSq = 0
  41. for (let i = 0; i < n; ++i) {
  42. const di = array[i]
  43. sumSq += di * di
  44. }
  45. return Math.sqrt(sumSq / n)
  46. }
  47. /** Fill an array with serial numbers starting from 0 until n - 1 (defaults to array.length) */
  48. export function fillSerial<T extends NumberArray> (array: T, n?: number) {
  49. for (let i = 0, il = n ? Math.min(n, array.length) : array.length; i < il; ++i) array[i] = i
  50. return array
  51. }
  52. export function arrayRemoveInPlace<T>(xs: T[], x: T) {
  53. let i = 0, l = xs.length, found = false;
  54. for (; i < l; i++) {
  55. if (xs[i] === x) {
  56. found = true;
  57. break;
  58. }
  59. }
  60. if (!found) return false;
  61. i++;
  62. for (; i < l; i++) {
  63. xs[i - 1] = xs[i];
  64. }
  65. xs.pop();
  66. return true;
  67. }