babylon.smartArray.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. module BABYLON {
  2. export class SmartArray<T> {
  3. public data: Array<T>;
  4. public length: number = 0;
  5. protected _id: number;
  6. [index: number]: T;
  7. constructor(capacity: number) {
  8. this.data = new Array(capacity);
  9. this._id = SmartArray._GlobalId++;
  10. }
  11. public push(value: T): void {
  12. this.data[this.length++] = value;
  13. if (this.length > this.data.length) {
  14. this.data.length *= 2;
  15. }
  16. }
  17. public forEach(func: (content: T) => void): void {
  18. for (var index = 0; index < this.length; index++) {
  19. func(this.data[index]);
  20. }
  21. }
  22. public sort(compareFn: (a: T, b: T) => number): void {
  23. this.data.sort(compareFn);
  24. }
  25. public reset(): void {
  26. this.length = 0;
  27. }
  28. public dispose(): void {
  29. this.reset();
  30. if (this.data) {
  31. this.data.length = 0;
  32. this.data = [];
  33. }
  34. }
  35. public concat(array: any): void {
  36. if (array.length === 0) {
  37. return;
  38. }
  39. if (this.length + array.length > this.data.length) {
  40. this.data.length = (this.length + array.length) * 2;
  41. }
  42. for (var index = 0; index < array.length; index++) {
  43. this.data[this.length++] = (array.data || array)[index];
  44. }
  45. }
  46. public indexOf(value: T): number {
  47. var position = this.data.indexOf(value);
  48. if (position >= this.length) {
  49. return -1;
  50. }
  51. return position;
  52. }
  53. public contains(value: T): boolean {
  54. return this.data.indexOf(value) !== -1;
  55. }
  56. // Statics
  57. private static _GlobalId = 0;
  58. }
  59. export class SmartArrayNoDuplicate<T> extends SmartArray<T> {
  60. private _duplicateId = 0;
  61. [index: number]: T;
  62. public push(value: T): void {
  63. super.push(value);
  64. if (!(<any>value).__smartArrayFlags) {
  65. (<any>value).__smartArrayFlags = {};
  66. }
  67. (<any>value).__smartArrayFlags[this._id] = this._duplicateId;
  68. }
  69. public pushNoDuplicate(value: T): boolean {
  70. if ((<any>value).__smartArrayFlags && (<any>value).__smartArrayFlags[this._id] === this._duplicateId) {
  71. return false;
  72. }
  73. this.push(value);
  74. return true;
  75. }
  76. public reset(): void {
  77. super.reset();
  78. this._duplicateId++;
  79. }
  80. public concatWithNoDuplicate(array: any): void {
  81. if (array.length === 0) {
  82. return;
  83. }
  84. if (this.length + array.length > this.data.length) {
  85. this.data.length = (this.length + array.length) * 2;
  86. }
  87. for (var index = 0; index < array.length; index++) {
  88. var item = (array.data || array)[index];
  89. this.pushNoDuplicate(item);
  90. }
  91. }
  92. }
  93. }