numbers.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. export function clamp(value, min, max) {
  6. return Math.min(Math.max(value, min), max);
  7. }
  8. export class MovingAverage {
  9. constructor() {
  10. this._n = 1;
  11. this._val = 0;
  12. }
  13. update(value) {
  14. this._val = this._val + (value - this._val) / this._n;
  15. this._n += 1;
  16. return this._val;
  17. }
  18. get value() {
  19. return this._val;
  20. }
  21. }
  22. export class SlidingWindowAverage {
  23. constructor(size) {
  24. this._n = 0;
  25. this._val = 0;
  26. this._values = [];
  27. this._index = 0;
  28. this._sum = 0;
  29. this._values = new Array(size);
  30. this._values.fill(0, 0, size);
  31. }
  32. update(value) {
  33. const oldValue = this._values[this._index];
  34. this._values[this._index] = value;
  35. this._index = (this._index + 1) % this._values.length;
  36. this._sum -= oldValue;
  37. this._sum += value;
  38. if (this._n < this._values.length) {
  39. this._n += 1;
  40. }
  41. this._val = this._sum / this._n;
  42. return this._val;
  43. }
  44. get value() {
  45. return this._val;
  46. }
  47. }