Created
April 7, 2021 14:37
-
-
Save Floofies/826ac20014761596f102e941b36ca46f to your computer and use it in GitHub Desktop.
Object Oriented Memory Manager
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
function MemManager(constructor, free, min, max, args = null) { | |
this.pool = []; | |
this.free = poolObj => { | |
if (!poolObj[MemManager.allocSym]) return; | |
poolObj[MemManager.allocSym] = false; | |
free(poolObj); | |
this.pool.push(poolObj); | |
}; | |
this.objConstructor = constructor; | |
this.args = args; | |
this.min = min; | |
this.max = max; | |
this.scaleUp(min); | |
} | |
MemManager.freeSym = Symbol("Object MemManager Member Marker"); | |
MemManager.allocSym = Symbol("Object MemManager Allocation Marker"); | |
MemManager.prototype.allocPoolObject = function(obj, pool) { | |
obj[MemManager.freeSym] = _=> pool.free(obj); | |
obj[MemManager.allocSym] = false; | |
return obj; | |
}; | |
MemManager.prototype.scaleUp = function(int) { | |
while (this.pool.length < int && this.pool.length < this.max) { | |
if (this.args === null) this.pool.push(this.allocPoolObject(new this.objConstructor(), this)); | |
else this.pool.push(this.allocPoolObject(new this.objConstructor(...this.args), this)); | |
} | |
}; | |
MemManager.prototype.scaleDown = function(int) { | |
while (this.pool.length > int && this.pool.length > this.min) { | |
this.pool.pop()[MemManager.freeSym] = null; | |
} | |
}; | |
MemManager.prototype.get = function() { | |
const poolObj = this.pool.pop(); | |
if (this.pool.length < this.min) this.scaleUp(this.min); | |
poolObj[MemManager.allocSym] = true; | |
return poolObj; | |
}; | |
module.exports = MemManager; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment