Source: lib/util/functional.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.util.Functional');
  7. goog.require('shaka.util.Timer');
  8. /**
  9. * @summary A set of functional utility functions.
  10. */
  11. shaka.util.Functional = class {
  12. /**
  13. * Creates a promise chain that calls the given callback for each element in
  14. * the array in a catch of a promise.
  15. *
  16. * e.g.:
  17. * Promise.reject().catch(callback(array[0])).catch(callback(array[1]));
  18. *
  19. * @param {!Array<ELEM>} array
  20. * @param {function(ELEM): !Promise<RESULT>} callback
  21. * @return {!Promise<RESULT>}
  22. * @template ELEM,RESULT
  23. */
  24. static createFallbackPromiseChain(array, callback) {
  25. return array.reduce((promise, elem) => {
  26. return promise.catch(() => callback(elem));
  27. }, Promise.reject());
  28. }
  29. /**
  30. * Returns the first array concatenated to the second; used to collapse an
  31. * array of arrays into a single array.
  32. *
  33. * @param {!Array<T>} all
  34. * @param {!Array<T>} part
  35. * @return {!Array<T>}
  36. * @template T
  37. */
  38. static collapseArrays(all, part) {
  39. return all.concat(part);
  40. }
  41. /**
  42. * A no-op function that ignores its arguments. This is used to suppress
  43. * unused variable errors.
  44. * @param {...*} args
  45. */
  46. static ignored(...args) {}
  47. /**
  48. * A no-op function. Useful in promise chains.
  49. */
  50. static noop() {}
  51. /**
  52. * Returns if the given value is not null; useful for filtering out null
  53. * values.
  54. *
  55. * @param {T} value
  56. * @return {boolean}
  57. * @template T
  58. */
  59. static isNotNull(value) {
  60. return value != null;
  61. }
  62. /**
  63. * Returns a Promise which is resolved only if |asyncProcess| is resolved, and
  64. * only if it is resolved in less than |seconds| seconds.
  65. *
  66. * If the returned Promise is resolved, it returns the same value as
  67. * |asyncProcess|.
  68. *
  69. * If |asyncProcess| fails, the returned Promise is rejected.
  70. * If |asyncProcess| takes too long, the returned Promise is rejected, but
  71. * |asyncProcess| is still allowed to complete.
  72. *
  73. * @param {number} seconds
  74. * @param {!Promise<T>} asyncProcess
  75. * @return {!Promise<T>}
  76. * @template T
  77. */
  78. static promiseWithTimeout(seconds, asyncProcess) {
  79. return Promise.race([
  80. asyncProcess,
  81. new Promise(((_, reject) => {
  82. new shaka.util.Timer(reject).tickAfter(seconds);
  83. })),
  84. ]);
  85. }
  86. };