NumMap.ts 1.8 KB

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