Source: lib/util/map_utils.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.util.MapUtils');
  7. /**
  8. * @summary A set of map/object utility functions.
  9. */
  10. shaka.util.MapUtils = class {
  11. /**
  12. * @param {!Object<KEY, VALUE>} object
  13. * @return {!Map<KEY, VALUE>}
  14. * @template KEY,VALUE
  15. */
  16. static asMap(object) {
  17. const map = new Map();
  18. for (const key of Object.keys(object)) {
  19. map.set(key, object[key]);
  20. }
  21. return map;
  22. }
  23. /**
  24. * @param {!Map<KEY, VALUE>} map
  25. * @return {!Object<KEY, VALUE>}
  26. * @template KEY,VALUE
  27. */
  28. static asObject(map) {
  29. const obj = {};
  30. map.forEach((value, key) => {
  31. obj[key] = value;
  32. });
  33. return obj;
  34. }
  35. /**
  36. * NOTE: This only works for simple value types and
  37. * will not be accurate if map values are objects!
  38. *
  39. * @param {Map<KEY, VALUE>} map1
  40. * @param {Map<KEY, VALUE>} map2
  41. * @return {boolean}
  42. * @template KEY,VALUE
  43. */
  44. static hasSameElements(map1, map2) {
  45. if (!map1 && !map2) {
  46. return true;
  47. } else if (map1 && !map2) {
  48. return false;
  49. } else if (map2 && !map1) {
  50. return false;
  51. }
  52. if (map1.size != map2.size) {
  53. return false;
  54. }
  55. for (const [key, val] of map1) {
  56. if (!map2.has(key)) {
  57. return false;
  58. }
  59. const val2 = map2.get(key);
  60. if (val2 != val || (val2 == undefined)) {
  61. return false;
  62. }
  63. }
  64. return true;
  65. }
  66. };