Source: lib/util/array_utils.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.util.ArrayUtils');
  7. /**
  8. * @namespace shaka.util.ArrayUtils
  9. * @summary Array utility functions.
  10. */
  11. shaka.util.ArrayUtils = class {
  12. /**
  13. * Returns whether the two values contain the same value. This correctly
  14. * handles comparisons involving NaN.
  15. * @param {T} a
  16. * @param {T} b
  17. * @return {boolean}
  18. * @template T
  19. */
  20. static defaultEquals(a, b) {
  21. // NaN !== NaN, so we need to special case it.
  22. if (typeof a === 'number' &&
  23. typeof b === 'number' && isNaN(a) && isNaN(b)) {
  24. return true;
  25. }
  26. return a === b;
  27. }
  28. /**
  29. * Remove given element from array (assumes no duplicates).
  30. * @param {!Array.<T>} array
  31. * @param {T} element
  32. * @template T
  33. */
  34. static remove(array, element) {
  35. const index = array.indexOf(element);
  36. if (index > -1) {
  37. array.splice(index, 1);
  38. }
  39. }
  40. /**
  41. * Count the number of items in the list that pass the check function.
  42. * @param {!Array.<T>} array
  43. * @param {function(T):boolean} check
  44. * @return {number}
  45. * @template T
  46. */
  47. static count(array, check) {
  48. let count = 0;
  49. for (const element of array) {
  50. count += check(element) ? 1 : 0;
  51. }
  52. return count;
  53. }
  54. /**
  55. * Determines if the given arrays contain equal elements in any order.
  56. *
  57. * @param {!Array.<T>} a
  58. * @param {!Array.<T>} b
  59. * @param {function(T, T):boolean=} compareFn
  60. * @return {boolean}
  61. * @template T
  62. */
  63. static hasSameElements(a, b, compareFn) {
  64. if (!compareFn) {
  65. compareFn = shaka.util.ArrayUtils.defaultEquals;
  66. }
  67. if (a.length != b.length) {
  68. return false;
  69. }
  70. const copy = b.slice();
  71. for (const item of a) {
  72. const idx = copy.findIndex((other) => compareFn(item, other));
  73. if (idx == -1) {
  74. return false;
  75. }
  76. // Since order doesn't matter, just swap the last element with
  77. // this one and then drop the last element.
  78. copy[idx] = copy[copy.length - 1];
  79. copy.pop();
  80. }
  81. return copy.length == 0;
  82. }
  83. /**
  84. * Determines if the given arrays contain equal elements in the same order.
  85. *
  86. * @param {!Array.<T>} a
  87. * @param {!Array.<T>} b
  88. * @param {function(T, T):boolean=} compareFn
  89. * @return {boolean}
  90. * @template T
  91. */
  92. static equal(a, b, compareFn) {
  93. if (!compareFn) {
  94. compareFn = shaka.util.ArrayUtils.defaultEquals;
  95. }
  96. if (a.length != b.length) {
  97. return false;
  98. }
  99. for (let i = 0; i < a.length; i++) {
  100. if (!compareFn(a[i], b[i])) {
  101. return false;
  102. }
  103. }
  104. return true;
  105. }
  106. };