Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. type KeyValuePair<T> = {
  2. Key: string;
  3. Value: T;
  4. }
  5.  
  6. interface IDictionary<T>
  7. {
  8. Add(key: string, value: T): boolean;
  9. Remove(key: string): boolean;
  10. ContainsKey(key: string): boolean;
  11.  
  12. Keys: string[];
  13. Values: T[];
  14. }
  15.  
  16. class Dictionary<T> implements IDictionary<T>
  17. {
  18. private items: { [index: string]: T } = {};
  19.  
  20. constructor(init?: { key: string; value: T; }[]) {
  21. if (init) {
  22. for (var x = 0; x < init.length; x++) {
  23. this.items[init[x].key] = init[x].value;
  24. }
  25. }
  26. }
  27.  
  28. public Add(key: string, value: T): boolean {
  29. if (this.ContainsKey(key))
  30. {
  31. return false;
  32. }
  33. this.items[key] = value;
  34. return this.ContainsKey(key);
  35. }
  36.  
  37. public Remove(key: string): boolean
  38. {
  39. if (this.ContainsKey(key))
  40. {
  41. delete this.items[key];
  42. return !this.ContainsKey(key);
  43. }
  44. return false;
  45. }
  46.  
  47. public get Keys(): string[]
  48. {
  49. return Object.keys(this.items);
  50. }
  51.  
  52. public get Values(): T[]
  53. {
  54. return Object.keys(this.items).map(key => this.items[key]);
  55. }
  56.  
  57. public get KeyValuePairs(): KeyValuePair<T>[] {
  58. return Object.keys(this.items).map(key =>
  59. (<KeyValuePair<T>>{ Key: key, Value: this.items[key] })
  60. );
  61. }
  62.  
  63. public ContainsKey(key: string)
  64. {
  65. if (typeof this.items[key] === "undefined") {
  66. return false;
  67. }
  68. return true;
  69. }
  70.  
  71. }
  72. let mydic = new Dictionary<string>();
  73. mydic.Add("siema", "lol");
  74. mydic.Add("siema2", "lol");
  75.  
  76. let button = document.createElement('button');
  77. button.textContent = "Say Hello";
  78. button.onclick = function () {
  79. for (let item of mydic.KeyValuePairs) {
  80. alert(item);
  81. }
  82.  
  83. }
  84.  
  85. document.body.appendChild(button);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement