collections.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. const hasOwnProperty = Object.prototype.hasOwnProperty;
  6. /**
  7. * Iterates over each entry in the provided dictionary. The iterator allows
  8. * to remove elements and will stop when the callback returns {{false}}.
  9. */
  10. export function forEach(from, callback) {
  11. for (let key in from) {
  12. if (hasOwnProperty.call(from, key)) {
  13. const result = callback({ key: key, value: from[key] }, function () {
  14. delete from[key];
  15. });
  16. if (result === false) {
  17. return;
  18. }
  19. }
  20. }
  21. }
  22. export class SetMap {
  23. constructor() {
  24. this.map = new Map();
  25. }
  26. add(key, value) {
  27. let values = this.map.get(key);
  28. if (!values) {
  29. values = new Set();
  30. this.map.set(key, values);
  31. }
  32. values.add(value);
  33. }
  34. delete(key, value) {
  35. const values = this.map.get(key);
  36. if (!values) {
  37. return;
  38. }
  39. values.delete(value);
  40. if (values.size === 0) {
  41. this.map.delete(key);
  42. }
  43. }
  44. forEach(key, fn) {
  45. const values = this.map.get(key);
  46. if (!values) {
  47. return;
  48. }
  49. values.forEach(fn);
  50. }
  51. }