Skip to content

Instantly share code, notes, and snippets.

@tomsoderlund
Created November 26, 2019 14:43
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 tomsoderlund/6cbe79a6bcc1593e304e3346c3f7ca4c to your computer and use it in GitHub Desktop.
Save tomsoderlund/6cbe79a6bcc1593e304e3346c3f7ca4c to your computer and use it in GitHub Desktop.
A resource pool e.g. for projects. Inspired by https://www.npmjs.com/package/generic-pool
/**
* parallelPool module
* @description A resource pool e.g. for projects. Inspired by https://www.npmjs.com/package/generic-pool
* @module parallelPool
* @author Tom Söderlund
*/
// Private functions
/* const projectPool = new ParallelPool({}) */
function ParallelPool ({ create, destroy }, { idleTimeoutMillis = 30000 } = {}) {
// Private
const items = {}
const timerId = setInterval(() => {
Object.keys(items).forEach(itemId => {
if ((Date.now() - items[itemId].time) > idleTimeoutMillis) {
this.release(itemId)
}
})
}, idleTimeoutMillis / 2)
// Get an instance e.g. a project
this.acquire = itemId => {
if (!items[itemId]) {
items[itemId] = { payload: create && create(itemId) }
}
items[itemId].time = Date.now()
return items[itemId].payload
}
// Release an instance e.g. a project
this.release = itemId => {
destroy && destroy(itemId)
delete items[itemId]
}
}
// Public API
module.exports = ParallelPool
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment