Source: lib/util/functional.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.Functional');
  18. /**
  19. * @namespace shaka.util.Functional
  20. * @summary A set of functional utility functions.
  21. */
  22. /**
  23. * Creates a promise chain that calls the given callback for each element in
  24. * the array in a catch of a promise.
  25. *
  26. * e.g.:
  27. * Promise.reject().catch(callback(array[0])).catch(callback(array[1]));
  28. *
  29. * @param {!Array.<ELEM>} array
  30. * @param {function(ELEM):!Promise.<RESULT>} callback
  31. * @return {!Promise.<RESULT>}
  32. * @template ELEM,RESULT
  33. */
  34. shaka.util.Functional.createFallbackPromiseChain = function(array, callback) {
  35. return array.reduce(function(callback, promise, elem) {
  36. return promise.catch(callback.bind(null, elem));
  37. }.bind(null, callback), Promise.reject());
  38. };
  39. /**
  40. * Returns the first array concatenated to the second; used to collapse an
  41. * array of arrays into a single array.
  42. *
  43. * @param {!Array.<T>} all
  44. * @param {!Array.<T>} part
  45. * @return {!Array.<T>}
  46. * @template T
  47. */
  48. shaka.util.Functional.collapseArrays = function(all, part) {
  49. return all.concat(part);
  50. };
  51. /**
  52. * A no-op function. Useful in promise chains.
  53. */
  54. shaka.util.Functional.noop = function() {};
  55. /**
  56. * Returns if the given value is not null; useful for filtering out null values.
  57. *
  58. * @param {T} value
  59. * @return {boolean}
  60. * @template T
  61. */
  62. shaka.util.Functional.isNotNull = function(value) {
  63. return value != null;
  64. };
  65. /**
  66. * Creates a function that returns whether the given value is equal to the given
  67. * value.
  68. *
  69. * @param {T} compare
  70. * @return {function(T):boolean}
  71. * @template T
  72. */
  73. shaka.util.Functional.isEqualFunc = function(compare) {
  74. return function(a) { return a == compare; };
  75. };
  76. /**
  77. * Creates a function that returns whether the given value is not equal to the
  78. * given value.
  79. *
  80. * @param {T} compare
  81. * @return {function(T):boolean}
  82. * @template T
  83. */
  84. shaka.util.Functional.isNotEqualFunc = function(compare) {
  85. return function(a) { return a != compare; };
  86. };