StringMap.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { ForeachMapAction, IMap } from "./IMap";
  2. /*
  3. * name;
  4. */
  5. export class StringMap<T> implements IMap<string, T> {
  6. private items: { [index: string]: T } = {};
  7. private count: number = 0;
  8. public Count(): number {
  9. return this.count;
  10. }
  11. public Add(key: string, value: T): T {
  12. if (!this.items.hasOwnProperty(key))
  13. this.count++;
  14. this.items[key] = value;
  15. return value;
  16. }
  17. public Remove(key: string): T {
  18. var val = this.items[key];
  19. delete this.items[key];
  20. this.count--;
  21. return val;
  22. }
  23. public ContainsKey(key: string): boolean {
  24. return this.items.hasOwnProperty(key);
  25. }
  26. public Value(key: string): T {
  27. return this.items[key];
  28. }
  29. public Replace(key: string, value: T): boolean {
  30. if (this.ContainsKey(key)) {
  31. this.items[key] = value;
  32. return true;
  33. }
  34. return false;
  35. }
  36. public Keys(): string[] {
  37. var keySet: string[] = [];
  38. for (var prop in this.items) {
  39. if (this.items.hasOwnProperty(prop))
  40. keySet.push(prop);
  41. }
  42. return keySet;
  43. }
  44. public Values(): T[] {
  45. var values: T[] = [];
  46. for (var prop in this.items) {
  47. if (this.items.hasOwnProperty(prop))
  48. values.push(this.items[prop]);
  49. }
  50. return values;
  51. }
  52. public Foreach(callback: ForeachMapAction<string, T>, thisArg?: any): void {
  53. if (callback) {
  54. for (var prop in this.items) {
  55. callback.call(thisArg, prop, this.items[prop]);
  56. }
  57. }
  58. }
  59. public Clear(): void {
  60. this.items = {};
  61. this.count = 0;
  62. }
  63. }