babylon.smartArray.ts 2.7 KB

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