Skip to content

Instantly share code, notes, and snippets.

@corbanbrook
Created February 9, 2017 17:19
Show Gist options
  • Save corbanbrook/e842a2eb477a5040bbb7073c9758285e to your computer and use it in GitHub Desktop.
Save corbanbrook/e842a2eb477a5040bbb7073c9758285e to your computer and use it in GitHub Desktop.
Simple object pool with fixed array size
//@flow
export default class ObjectPool {
size: number
head: number
items: Array<any>
renewCallback: ?Function
releaseCallback: ?Function
constructor(size: number, init: Function, renewCallback: ?Function, releaseCallback: ?Function) {
this.size = size
this.items = new Array(size)
this.head = -1
this.renewCallback = renewCallback
this.releaseCallback = releaseCallback
// Init objects
for (let idx = 0; idx < size; idx++) { this.release(init()) }
}
// The length of active objects taken from the pool
get length() : number {
return this.size - this.head - 1
}
// Take an object from the pool
renew() {
if (this.head >= 0) {
const object = this.items[this.head--]
if (typeof this.renewCallback === 'function') { this.renewCallback(object) }
return object
}
}
// Release an object back into the pool
release(object: any) {
if (this.head < this.size - 1) {
this.items[++this.head] = object
if (typeof this.releaseCallback === 'function') { this.releaseCallback(object) }
}
}
// Peak at the next object in the pool
peekNext() {
if (this.head >= 0) {
return this.items[this.head]
}
}
// Peak at the last object in the pool
peekLast() {
if (this.head >= 0) {
return this.items[0]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment