Dictionary.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. /**
  2. * 字典型的数据存取类。
  3. */
  4. export class Dictionary<T> {
  5. private m_keys: any[] = [];
  6. private m_values: T[] = [];
  7. public get length(): number {
  8. return this.m_keys.length;
  9. }
  10. /**
  11. * 获取所有的子元素列表。
  12. */
  13. public get values(): T[] {
  14. return this.m_values.concat();
  15. }
  16. /**
  17. * 获取所有的子元素键名列表。
  18. */
  19. public get keys(): any[] {
  20. return this.m_keys.concat();
  21. }
  22. /**
  23. * 获取指定对象的键名索引。
  24. * @param key 键名对象。
  25. * @return 键名索引。
  26. */
  27. public indexOfKey(key: any): number {
  28. return this.m_keys.indexOf(key);
  29. }
  30. public indexOfValue(val: T) {
  31. return this.m_values.indexOf(val);
  32. }
  33. /**
  34. * 通过value得到对应的key
  35. */
  36. public getKeyByValue(value: T): any {
  37. return this.m_keys[this.indexOfValue(value)];
  38. }
  39. /**
  40. * 添加指定键名的值。
  41. * @param key 键名。
  42. * @param value 值。
  43. */
  44. public add(key: any, value: T): void {
  45. var index: number = this.indexOfKey(key);
  46. if (index >= 0) {
  47. this.m_values[index] = value;
  48. } else {
  49. this.m_keys.push(key);
  50. this.m_values.push(value);
  51. }
  52. }
  53. /**
  54. * 返回指定键名的值。
  55. * @param key 键名对象。
  56. * @return 指定键名的值。
  57. */
  58. public get(key: any): T {
  59. var index: number = this.indexOfKey(key);
  60. if (index >= 0) {
  61. return this.m_values[index];
  62. }
  63. return null;
  64. }
  65. /**
  66. * 设置指定key的值。
  67. * @param key 键名对象。
  68. * @return 指定键名的值。
  69. */
  70. public set(key: any, value: T) {
  71. var index: number = this.indexOfKey(key);
  72. if (index >= 0) {
  73. this.m_values[index] = value;
  74. }else{
  75. this.add(key, value);
  76. }
  77. }
  78. /**
  79. * 移除指定键名的值。
  80. * @param key 键名对象。
  81. * @return 是否成功移除。
  82. */
  83. public remove(key: any): T {
  84. var index: number = this.indexOfKey(key);
  85. if (index >= 0) {
  86. this.m_keys.splice(index, 1);
  87. return this.m_values.splice(index, 1)[0];
  88. }
  89. return null;
  90. }
  91. public containsKey(key: any): boolean {
  92. var index: number = this.indexOfKey(key);
  93. if (index >= 0) {
  94. return true;
  95. }
  96. return false;
  97. }
  98. /**
  99. * 清除此对象的键名列表和键值列表。
  100. */
  101. public clear() {
  102. this.m_keys.length = 0;
  103. this.m_values.length = 0;
  104. }
  105. public setLength(num: number) {
  106. this.m_keys.length = num;
  107. this.m_values.length = num;
  108. }
  109. /**
  110. * 随机获取一条数据
  111. */
  112. public getRandomData(): T {
  113. var index: number = Math.random() * this.keys.length << 0;
  114. return this.m_values[index];
  115. }
  116. }