Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Created November 25, 2019 09:47
Show Gist options
  • Save bartwttewaall/6dbf277cc7e0ad1f097bc6ed6843fe9f to your computer and use it in GitHub Desktop.
Save bartwttewaall/6dbf277cc7e0ad1f097bc6ed6843fe9f to your computer and use it in GitHub Desktop.
Modified getify/deePool with additional functionality
// modified https://github.com/getify/deePool
const EMPTY_SLOT = Object.freeze(Object.create(null));
export default class ObjectPool {
constructor(objectFactory = () => {}, initialSize) {
this.objectFactory = objectFactory;
this.objPool = [];
this.nextFreeSlot = null;
if (!!initialSize) this.grow(initialSize);
}
pop() {
if (this.nextFreeSlot == null || this.nextFreeSlot == this.objPool.length) {
this.grow(this.objPool.length || 5);
}
const objToUse = this.objPool[this.nextFreeSlot];
this.objPool[this.nextFreeSlot++] = EMPTY_SLOT;
return objToUse;
}
push(obj) {
if (this.nextFreeSlot == null || this.nextFreeSlot == -1) {
this.objPool[this.objPool.length] = obj;
} else {
this.objPool[--this.nextFreeSlot] = obj;
}
}
grow(count = this.objPool.length) {
if (count > 0 && this.nextFreeSlot == null) {
this.nextFreeSlot = 0;
}
if (count > 0) {
const curLen = this.objPool.length;
this.objPool.length += Number(count);
for (let i = curLen, il = this.objPool.length; i < il; i++) {
this.objPool[i] = this.objectFactory();
}
}
return this.objPool.length;
}
size() {
return this.objPool.length;
}
numEmpty() {
return this.objPool.filter((value) => value === EMPTY_SLOT).length;
}
numStored() {
return this.objPool.length - this.numEmpty();
}
toString() {
return "[ ObjectPool { available:" + this.numStored() + "/" + this.objPool.length + " } ]";
}
forEach(callback = () => void 0) {
this.objPool.forEach((value, index, array) => {
if (value !== EMPTY_SLOT) callback(value, index, array);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment