babylon.smartCollection.ts 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. module BABYLON {
  2. export class SmartCollection {
  3. public count = 0;
  4. public items: any;
  5. private _keys: string[];
  6. private _initialCapacity: number;
  7. constructor(capacity: number = 10) {
  8. this._initialCapacity = capacity;
  9. this.items = {};
  10. this._keys = new Array(this._initialCapacity);
  11. }
  12. public add(key: any, item: any): number {
  13. if (this.items[key] != undefined) {
  14. return -1;
  15. }
  16. this.items[key] = item;
  17. //literal keys are always strings, but we keep source type of key in _keys array
  18. this._keys[this.count++] = key;
  19. if (this.count > this._keys.length) {
  20. this._keys.length *= 2;
  21. }
  22. return this.count;
  23. }
  24. public remove(key: any): number {
  25. if (this.items[key] == undefined) {
  26. return -1;
  27. }
  28. return this.removeItemOfIndex(this.indexOf(key));
  29. }
  30. public removeItemOfIndex(index: number): number {
  31. if (index < this.count && index > -1) {
  32. delete this.items[this._keys[index]];
  33. //here, shifting by hand is better optimised than .splice
  34. while (index < this.count) {
  35. this._keys[index] = this._keys[index + 1]; index++;
  36. }
  37. }
  38. else {
  39. return -1;
  40. }
  41. return --this.count;
  42. }
  43. public indexOf(key: any): number {
  44. for (var i = 0; i !== this.count; i++) {
  45. if (this._keys[i] === key) {
  46. return i;
  47. }
  48. }
  49. return -1;
  50. }
  51. public item(key: any): any {
  52. return this.items[key];
  53. }
  54. public getAllKeys(): any[] {
  55. if (this.count > 0) {
  56. var keys = new Array(this.count);
  57. for (var i = 0; i < this.count; i++) {
  58. keys[i] = this._keys[i];
  59. }
  60. return keys;
  61. }
  62. else {
  63. return undefined;
  64. }
  65. }
  66. public getKeyByIndex(index: number): any {
  67. if (index < this.count && index > -1) {
  68. return this._keys[index];
  69. }
  70. else {
  71. return undefined;
  72. }
  73. }
  74. public getItemByIndex(index: number): any {
  75. if (index < this.count && index > -1) {
  76. return this.items[this._keys[index]];
  77. }
  78. else {
  79. return undefined;
  80. }
  81. }
  82. public empty(): void {
  83. if (this.count > 0) {
  84. this.count = 0;
  85. this.items = {};
  86. this._keys = new Array(this._initialCapacity);
  87. }
  88. }
  89. }
  90. }