Source: lib/util/iterables.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.Iterables');
  18. /**
  19. * Recreations of Array-like functions so that they work on any iterable
  20. * type.
  21. * @final
  22. */
  23. shaka.util.Iterables = class {
  24. /**
  25. * @param {!Iterable.<FROM>|!Iterator.<FROM>} iterable
  26. * @param {function(FROM):TO} mapping
  27. * @return {!Iterable.<TO>}
  28. * @template FROM,TO
  29. */
  30. static map(iterable, mapping) {
  31. const array = [];
  32. for (const x of iterable) { array.push(mapping(x)); }
  33. return array;
  34. }
  35. /**
  36. * @param {!Iterable.<T>|!Iterator.<T>} iterable
  37. * @param {function(T):boolean} test
  38. * @return {boolean}
  39. * @template T
  40. */
  41. static every(iterable, test) {
  42. for (const x of iterable) {
  43. if (!test(x)) { return false; }
  44. }
  45. return true;
  46. }
  47. /**
  48. * @param {!Iterable.<T>|!Iterator.<T>} iterable
  49. * @param {function(T):boolean} test
  50. * @return {boolean}
  51. * @template T
  52. */
  53. static some(iterable, test) {
  54. for (const x of iterable) {
  55. if (test(x)) { return true; }
  56. }
  57. return false;
  58. }
  59. };