Created
March 16, 2018 00:44
-
-
Save luruke/08e02561d57d95d0875b5e70996c0a98 to your computer and use it in GitHub Desktop.
ObjectPool.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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