Source: lib/util/multi_map.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.MultiMap');
  18. /**
  19. * A simple multimap template.
  20. * @constructor
  21. * @struct
  22. * @template T
  23. */
  24. shaka.util.MultiMap = function() {
  25. /** @private {!Object.<string, !Array.<T>>} */
  26. this.map_ = {};
  27. };
  28. /**
  29. * Add a key, value pair to the map.
  30. * @param {string} key
  31. * @param {T} value
  32. */
  33. shaka.util.MultiMap.prototype.push = function(key, value) {
  34. if (this.map_.hasOwnProperty(key)) {
  35. this.map_[key].push(value);
  36. } else {
  37. this.map_[key] = [value];
  38. }
  39. };
  40. /**
  41. * Get a list of values by key.
  42. * @param {string} key
  43. * @return {Array.<T>} or null if no such key exists.
  44. */
  45. shaka.util.MultiMap.prototype.get = function(key) {
  46. var list = this.map_[key];
  47. // slice() clones the list so that it and the map can each be modified
  48. // without affecting the other.
  49. return list ? list.slice() : null;
  50. };
  51. /**
  52. * Get a list of all values.
  53. * @return {!Array.<T>}
  54. */
  55. shaka.util.MultiMap.prototype.getAll = function() {
  56. var list = [];
  57. for (var key in this.map_) {
  58. list.push.apply(list, this.map_[key]);
  59. }
  60. return list;
  61. };
  62. /**
  63. * Remove a specific value, if it exists.
  64. * @param {string} key
  65. * @param {T} value
  66. */
  67. shaka.util.MultiMap.prototype.remove = function(key, value) {
  68. var list = this.map_[key];
  69. if (!list) return;
  70. for (var i = 0; i < list.length; ++i) {
  71. if (list[i] == value) {
  72. list.splice(i, 1);
  73. --i;
  74. }
  75. }
  76. };
  77. /**
  78. * Clear all keys and values from the multimap.
  79. */
  80. shaka.util.MultiMap.prototype.clear = function() {
  81. this.map_ = {};
  82. };