Created
November 26, 2019 14:43
-
-
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
This file contains hidden or 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
/** | |
* 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