Source: lib/util/map_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.MapUtils');
  18. /**
  19. * @namespace shaka.util.MapUtils
  20. * @summary A set of map/object utility functions.
  21. */
  22. /**
  23. * Returns true if the map is empty; otherwise, returns false.
  24. *
  25. * @param {Object.<KEY, VALUE>} object
  26. * @return {boolean}
  27. * @template KEY,VALUE
  28. */
  29. shaka.util.MapUtils.empty = function(object) {
  30. return !object || Object.keys(object).length == 0;
  31. };
  32. /**
  33. * Gets the map's values.
  34. *
  35. * @param {!Object.<KEY, VALUE>} object
  36. * @return {!Array.<VALUE>}
  37. * @template KEY,VALUE
  38. */
  39. shaka.util.MapUtils.values = function(object) {
  40. return Object.keys(object).map(function(key) { return object[key]; });
  41. };
  42. /**
  43. * Converts the values in the given Map to a different value.
  44. *
  45. * @param {!Object.<KEY, VALUE>} object
  46. * @param {function(VALUE, KEY=):OUTPUT} callback
  47. * @return {!Object.<KEY, OUTPUT>}
  48. * @template KEY,VALUE,OUTPUT
  49. */
  50. shaka.util.MapUtils.map = function(object, callback) {
  51. return Object.keys(object).reduce(function(ret, key) {
  52. var value = object[key];
  53. ret[key] = callback(value, key);
  54. return ret;
  55. }, {});
  56. };
  57. /**
  58. * Returns true if every entry matches the predicate.
  59. *
  60. * @param {!Object.<KEY, VALUE>} object
  61. * @param {function(KEY, VALUE):boolean} callback
  62. * @return {boolean}
  63. * @template KEY,VALUE
  64. */
  65. shaka.util.MapUtils.every = function(object, callback) {
  66. return Object.keys(object).every(function(key) {
  67. return callback(key, object[key]);
  68. });
  69. };
  70. /**
  71. * Invokes the callback for each entry in the map.
  72. *
  73. * @param {!Object.<KEY, VALUE>} object
  74. * @param {function(KEY, VALUE)} callback
  75. * @template KEY,VALUE
  76. */
  77. shaka.util.MapUtils.forEach = function(object, callback) {
  78. Object.keys(object).forEach(function(key) {
  79. callback(key, object[key]);
  80. });
  81. };