Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Created April 19, 2018 12:09
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 amatiasq/bd225e810d31893f496f5b191d1556c5 to your computer and use it in GitHub Desktop.
Save amatiasq/bd225e810d31893f496f5b191d1556c5 to your computer and use it in GitHub Desktop.
Vector created
Initialized Vector(0, 0)
Vector created
Initialized Vector(10, 10)
Rectangle created
Vector created
Initialized Vector(10, 10)
Initialized Rectangle(0, 0, 10, 10)
Disposed Rectangle(0, 0, 10, 10)
Disposed Vector(0, 0)
Disposed Vector(10, 10)
Disposed Vector(10, 10)
Initialized Vector(1, 2)
Initialized Vector(15, 15)
Initialized Vector(16, 17)
Initialized Rectangle(1, 2, 15, 15)
POTATO true
function pool(Class, serialize) {
const pool = [];
const original = Class.prototype.dispose;
Class.get = get;
Class.dispose = dispose;
Class.prototype.dispose = instanceDispose;
return Class;
function get(...args) {
const instance = pool.pop() || new Class();
instance.init(...args);
instance.isDisposed = false;
console.log(`Initialized ${instance}`);
return instance;
}
function dispose(instance) {
console.log(`Disposed ${instance}`);
if (typeof original === 'function') {
original.call(instance);
}
instance.isDisposed = true;
pool.push(instance);
}
function instanceDispose() {
dispose(this);
}
}
class Vector {
constructor() {
console.log('Vector created');
}
init(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `Vector(${this.x}, ${this.y})`;
}
}
class Rectangle {
constructor() {
console.log('Rectangle created');
}
get x() { return this.pos.x }
get y() { return this.pos.y }
get width() { return this.size.x }
get height() { return this.size.y }
init(pos, size) {
this.pos = pos;
this.size = size;
this.end = Vector.get(pos.x + size.x, pos.y + size.y);
}
dispose() {
this.pos.dispose();
this.size.dispose();
this.end.dispose();
}
toString() {
return `Rectangle(${this.x}, ${this.y}, ${this.width}, ${this.height})`;
}
}
pool(Vector);
pool(Rectangle);
const rectangle = Rectangle.get(Vector.get(0, 0), Vector.get(10, 10));
rectangle.dispose();
const other = Rectangle.get(Vector.get(1, 2), Vector.get(15, 15));
console.log('POTATO', rectangle === other);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment