Skip to content

Instantly share code, notes, and snippets.

@YonatanKra
Last active June 19, 2023 07:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save YonatanKra/3f0188fcbb35853b8732342e4a52d57e to your computer and use it in GitHub Desktop.
Save YonatanKra/3f0188fcbb35853b8732342e4a52d57e to your computer and use it in GitHub Desktop.
class PoolObject {
constructor(data) {
this.data = data;
this.nextFree = null;
this.previousFree = null;
}
}
class Pool {
constructor(objCreator, objReseter, initialSize = 5000) {
this._pool = [];
this.objCreator = objCreator;
this.objReseter = objReseter;
for (let i = 0; i < initialSize; i++) {
this.addNewObject(this.newPoolObject());
}
}
addNewObject(obj) {
this._pool.push(obj);
this.release(obj);
return obj;
}
release(poolObject) {
// flag as free
poolObject.free = true;
// set in the queue
poolObject.nextFree = null;
poolObject.previousFree = this.lastFree;
// if we had a last free, set the last free's next as the new poolObject
// otherwise, this is the first free!
if (poolObject.previousFree) {
this.lastFree.nextFree = poolObject;
} else {
this.nextFree = poolObject;
}
// set the new object as the last in the queue
this.lastFree = poolObject;
// reset the object if needed
this.objReseter(poolObject);
}
getFree() {
// if we have a free one, get it - otherwise create it
const freeObject = this.nextFree ? this.nextFree : this.addNewObject(this.newPoolObject());
// flag as used
freeObject.free = false;
// the next free is the object's next free
this.nextFree = freeObject.nextFree;
// if there's nothing afterwards, the lastFree is null as well
if (!this.nextFree) this.lastFree = null;
// return the now not free object
return freeObject;
}
newPoolObject() {
const data = this.objCreator();
return new PoolObject(data, this.lastFree, this.nextFree);
}
releaseAll() {
this._pool.forEach(item => this.release(item));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment