Source: lib/util/iterables.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.util.Iterables');
  7. /**
  8. * Recreations of Array-like functions so that they work on any iterable
  9. * type.
  10. * @final
  11. */
  12. shaka.util.Iterables = class {
  13. /**
  14. * @param {!Iterable.<FROM>} iterable
  15. * @param {function(FROM):TO} mapping
  16. * @return {!Iterable.<TO>}
  17. * @template FROM,TO
  18. */
  19. static map(iterable, mapping) {
  20. const array = [];
  21. for (const x of iterable) {
  22. array.push(mapping(x));
  23. }
  24. return array;
  25. }
  26. /**
  27. * @param {!Iterable.<T>} iterable
  28. * @param {function(T):boolean} test
  29. * @return {boolean}
  30. * @template T
  31. */
  32. static every(iterable, test) {
  33. for (const x of iterable) {
  34. if (!test(x)) {
  35. return false;
  36. }
  37. }
  38. return true;
  39. }
  40. /**
  41. * @param {!Iterable.<T>} iterable
  42. * @param {function(T):boolean} test
  43. * @return {boolean}
  44. * @template T
  45. */
  46. static some(iterable, test) {
  47. for (const x of iterable) {
  48. if (test(x)) {
  49. return true;
  50. }
  51. }
  52. return false;
  53. }
  54. /**
  55. * Iterate over an iterable object and return only the items that |filter|
  56. * returns true for.
  57. *
  58. * @param {!Iterable.<T>} iterable
  59. * @param {function(T):boolean} filter
  60. * @return {!Array.<T>}
  61. * @template T
  62. */
  63. static filter(iterable, filter) {
  64. const out = [];
  65. for (const x of iterable) {
  66. if (filter(x)) {
  67. out.push(x);
  68. }
  69. }
  70. return out;
  71. }
  72. };