babylon.smartArray.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 pushNoDuplicate(value): boolean {
  22. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23. return false;
  24. }
  25. this.push(value);
  26. return true;
  27. }
  28. public sort(compareFn): void {
  29. this.data.sort(compareFn);
  30. }
  31. public reset(): void {
  32. this.length = 0;
  33. this._duplicateId++;
  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 concatWithNoDuplicate(array: any): void {
  47. if (array.length === 0) {
  48. return;
  49. }
  50. if (this.length + array.length > this.data.length) {
  51. this.data.length = (this.length + array.length) * 2;
  52. }
  53. for (var index = 0; index < array.length; index++) {
  54. var item = (array.data || array)[index];
  55. this.pushNoDuplicate(item);
  56. }
  57. }
  58. public indexOf(value): number {
  59. var position = this.data.indexOf(value);
  60. if (position >= this.length) {
  61. return -1;
  62. }
  63. return position;
  64. }
  65. // Statics
  66. private static _GlobalId = 0;
  67. }
  68. }