Skip to content

Instantly share code, notes, and snippets.

@luruke
Created March 16, 2018 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luruke/08e02561d57d95d0875b5e70996c0a98 to your computer and use it in GitHub Desktop.
Save luruke/08e02561d57d95d0875b5e70996c0a98 to your computer and use it in GitHub Desktop.
ObjectPool.js
export default class ObjectPool {
constructor(options = {}) {
this.options = Object.assign({
number: 10,
Create() {
return {};
},
}, options);
this.available = [];
this.busy = [];
this.init();
}
init() {
for (let i = 0; i < this.options.number; i++) {
const instance = new this.options.Create();
this.available.push(instance);
}
}
get() {
if (!this.available.length) {
throw new Error(`ObjectPool has no more items! default was ${this.number}`);
}
const instance = this.available.shift();
instance._busy = true;
this.busy.push(instance);
return instance;
}
free(object) {
const index = this.busy.indexOf(object);
if (index > -1) {
object._busy = false;
this.busy.splice(index, 1);
this.available.push(object);
}
}
freeAll() {
this.busy.forEach(object => {
object._busy = false;
this.available.push(object);
});
this.busy = [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment