Source: lib/util/array_utils.js

  1. /**
  2. * @license
  3. * Copyright 2016 Google Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. goog.provide('shaka.util.ArrayUtils');
  18. /**
  19. * @namespace shaka.util.ArrayUtils
  20. * @summary Array utility functions.
  21. */
  22. /**
  23. * Remove duplicate entries from an array. Order N^2, so use with caution.
  24. * @param {!Array.<T>} array
  25. * @param {function(T, T): boolean=} opt_compareFn An optional function which
  26. * will be used to compare items in the array.
  27. * @return {!Array.<T>}
  28. * @template T
  29. */
  30. shaka.util.ArrayUtils.removeDuplicates = function(array, opt_compareFn) {
  31. var result = [];
  32. for (var i = 0; i < array.length; ++i) {
  33. var matchFound = false;
  34. for (var j = 0; j < result.length; ++j) {
  35. matchFound = opt_compareFn ? opt_compareFn(array[i], result[j]) :
  36. array[i] === result[j];
  37. if (matchFound) break;
  38. }
  39. if (!matchFound) {
  40. result.push(array[i]);
  41. }
  42. }
  43. return result;
  44. };
  45. /**
  46. * Find an item in an array. For use when comparison of entries via == will
  47. * not suffice.
  48. * @param {!Array.<T>} array
  49. * @param {T} value
  50. * @param {function(T, T): boolean} compareFn A function which will be used to
  51. * compare items in the array.
  52. * @return {number} The index, or -1 if not found.
  53. * @template T
  54. */
  55. shaka.util.ArrayUtils.indexOf = function(array, value, compareFn) {
  56. for (var i = 0; i < array.length; ++i) {
  57. if (compareFn(array[i], value)) {
  58. return i;
  59. }
  60. }
  61. return -1;
  62. };
  63. /**
  64. * Remove given element from array (assumes no duplicates).
  65. * @param {!Array.<T>} array
  66. * @param {T} element
  67. * @template T
  68. */
  69. shaka.util.ArrayUtils.remove = function(array, element) {
  70. var index = array.indexOf(element);
  71. if (index > -1)
  72. array.splice(index, 1);
  73. };