Skip to content

Instantly share code, notes, and snippets.

@donmccurdy
Created July 21, 2019 05:29
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 donmccurdy/4d97b67f1c0ddcccdd07bd2b89605949 to your computer and use it in GitHub Desktop.
Save donmccurdy/4d97b67f1c0ddcccdd07bd2b89605949 to your computer and use it in GitHub Desktop.
Simple pool implementation.
/**
* Simple pool of generic objects.
* @param {function():T} Function that creates a resource.
* @param {function():T} Function that resets a resource.
*/
function Pool ( factory, reset ) {
this.factory = factory;
this.reset = reset;
this.resources = [];
};
/**
* @return {T}
*/
Pool.prototype.obtain = function () {
if (this.resources.length > 0) {
return this.resources.pop();
} else {
return this.factory();
}
};
/**
* @param {T} resource
*/
Pool.prototype.recycle = function ( resource ) {
if (this.reset) this.reset(resource);
this.resources.push(resource);
};
module.exports = Pool;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment