Pool.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. class Pool {
  2. constructor(e, t, r, n, ...o) {
  3. E(this, "objCreator");
  4. E(this, "objReseter");
  5. E(this, "_pool");
  6. E(this, "lastFree");
  7. E(this, "nextFree");
  8. E(this, "capacity");
  9. this._pool = [],
  10. this.objCreator = e,
  11. this.objReseter = t;
  12. for (let a = 0; a < n; a++)
  13. this.addNewObject(this.newPoolObject(...o));
  14. this.capacity = r
  15. }
  16. addNewObject(e) {
  17. return this._pool.push(e),
  18. this.release(e),
  19. e
  20. }
  21. release(e) {
  22. e.free = !0,
  23. e.nextFree = null,
  24. e.previousFree = this.lastFree,
  25. this.lastFree ? this.lastFree.nextFree = e : this.nextFree = e,
  26. this.lastFree = e,
  27. this.objReseter(e)
  28. }
  29. getFree(...e) {
  30. const t = this.nextFree ? this.nextFree : this.addNewObject(this.newPoolObject(...e));
  31. return t.free = !1,
  32. this.nextFree = t.nextFree,
  33. this.nextFree || (this.lastFree = null),
  34. t
  35. }
  36. newPoolObject(...e) {
  37. const t = this.objCreator(...e);
  38. return new PoolObject(t,this.nextFree,this.lastFree)
  39. }
  40. releaseAll() {
  41. this._pool.forEach(e=>this.release(e))
  42. }
  43. clean(e=0, ...t) {
  44. let r = this.nextFree;
  45. if (!r)
  46. return;
  47. let n = 0;
  48. for (; r; )
  49. n += 1,
  50. r = r.nextFree;
  51. let o = !1;
  52. if (n > e && this._pool.length > this.capacity && (o = !0),
  53. o)
  54. for (r = this.nextFree; r; ) {
  55. r.free = !1,
  56. this.nextFree = r.nextFree;
  57. const a = this._pool.indexOf(r);
  58. this._pool.splice(a, 1),
  59. this.nextFree || (this.lastFree = null),
  60. r == null || r.dispose(),
  61. r = this.nextFree
  62. }
  63. }
  64. }