Source: lib/util/multi_map.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.util.MultiMap');
  7. /**
  8. * @summary A simple multimap template.
  9. * @template T
  10. */
  11. shaka.util.MultiMap = class {
  12. constructor() {
  13. /** @private {!Object.<string, !Array.<T>>} */
  14. this.map_ = {};
  15. }
  16. /**
  17. * Add a key, value pair to the map.
  18. * @param {string} key
  19. * @param {T} value
  20. */
  21. push(key, value) {
  22. if (this.map_.hasOwnProperty(key)) {
  23. this.map_[key].push(value);
  24. } else {
  25. this.map_[key] = [value];
  26. }
  27. }
  28. /**
  29. * Get a list of values by key.
  30. * @param {string} key
  31. * @return {Array.<T>} or null if no such key exists.
  32. */
  33. get(key) {
  34. const list = this.map_[key];
  35. // slice() clones the list so that it and the map can each be modified
  36. // without affecting the other.
  37. return list ? list.slice() : null;
  38. }
  39. /**
  40. * Get a list of all values.
  41. * @return {!Array.<T>}
  42. */
  43. getAll() {
  44. const list = [];
  45. for (const key in this.map_) {
  46. list.push(...this.map_[key]);
  47. }
  48. return list;
  49. }
  50. /**
  51. * Remove a specific value, if it exists.
  52. * @param {string} key
  53. * @param {T} value
  54. */
  55. remove(key, value) {
  56. if (!(key in this.map_)) {
  57. return;
  58. }
  59. this.map_[key] = this.map_[key].filter((i) => i != value);
  60. }
  61. /**
  62. * Clear all keys and values from the multimap.
  63. */
  64. clear() {
  65. this.map_ = {};
  66. }
  67. /**
  68. * @param {function(string, !Array.<T>)} callback
  69. */
  70. forEach(callback) {
  71. for (const key in this.map_) {
  72. callback(key, this.map_[key]);
  73. }
  74. }
  75. };