Created
July 21, 2019 05:29
-
-
Save donmccurdy/4d97b67f1c0ddcccdd07bd2b89605949 to your computer and use it in GitHub Desktop.
Simple pool implementation.
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
/** | |
* 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