Implement a `createPool(factory, maxSize)` that reuses objects. `acquire()` gets an object, `release(obj)` returns it to the pool.
Problem Statement
Implement a `createPool(factory, maxSize)` that reuses objects. `acquire()` gets an object, `release(obj)` returns it to the pool.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
An object pool avoids expensive creation by reusing instances.
š” Hint 2:
Maintain a list of available objects. On acquire, take one; on release, put it back.
š” Hint 3:
If pool is empty on acquire, create a new object with factory().
ā
Solution:
```javascript
function createPool(factory, maxSize) {
const available = [];
let created = 0;
return {
acquire() {
if (available.length > 0) return available.pop();
if (created < maxSize) { created++; return factory(); }
throw new Error("Pool exhausted");
},
release(obj) { available.push(obj); },
size() { return { available: available.length, created }; }
};
}
```