You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MathUtil.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * The method will increase the given number by 1. If the given counter is equal
  3. * or greater to {@link Number.MAX_SAFE_INTEGER} then it will be rolled back to
  4. * 1.
  5. * @param {number} number - An integer counter value to be incremented.
  6. * @return {number} the next counter value increased by 1 (see the description
  7. * above for exception).
  8. */
  9. export function safeCounterIncrement(number) {
  10. let nextValue = number;
  11. if (number >= Number.MAX_SAFE_INTEGER) {
  12. nextValue = 0;
  13. }
  14. return nextValue + 1;
  15. }
  16. /**
  17. * Calculates the average value of am Array of numbers.
  18. *
  19. * @param {Float32Array} valueArray - Array of numbers.
  20. * @returns {number} - Number array average.
  21. */
  22. export function calculateAverage(valueArray) {
  23. return valueArray.length > 0 ? valueArray.reduce((a, b) => a + b) / valueArray.length : 0;
  24. }
  25. /**
  26. * Returns only the positive values from an array of numbers.
  27. *
  28. * @param {Float32Array} valueArray - Array of vad scores.
  29. * @returns {Array} - Array of positive numbers.
  30. */
  31. export function filterPositiveValues(valueArray) {
  32. return valueArray.filter(value => value >= 0);
  33. }
  34. /**
  35. * This class calculates a simple running average that continually changes
  36. * as more data points are collected and added.
  37. */
  38. export class RunningAverage {
  39. /**
  40. * Creates an instance of the running average calculator.
  41. */
  42. constructor() {
  43. this.average = 0;
  44. this.n = 0;
  45. }
  46. /**
  47. * Adds a new data point to the existing set of values and recomputes
  48. * the running average.
  49. * @param {number} value
  50. * @returns {void}
  51. */
  52. addNext(value) {
  53. if (typeof value !== 'number') {
  54. return;
  55. }
  56. this.n += 1;
  57. this.average = this.average + ((value - this.average) / this.n);
  58. }
  59. /**
  60. * Obtains the average value for the current subset of values.
  61. * @returns {number} - computed average.
  62. */
  63. getAverage() {
  64. return this.average;
  65. }
  66. }