This was just an experiment to see if it was possible to build a stateless builder in ES6. I was able to do it, but when I took it a step further I got stuck trying to DRY it out.
In this case, we have a MoveableBuilder and a ParticleBuilder. A Particle is a Moveable, so the ParticleBuilder could reuse a lot of the code from the MoveableBuilder. Unfortunately, I haven't been able to figure out how to combine the two functions in an elegant way.
function ParticleBuilder(coordinates = [], vector = [], lifespan = 255, decay = 1) {
const self = this;
this.at = (...coordinates) =>
new self.constructor(coordinates, vector, lifespan, decay);
this.facing = (...vector) =>
new self.constructor(coordinates, vector, lifespan, decay);
this.lifespan = (lifespan) =>
new self.constructor(coordinates, vector, lifespan, decay);
this.decay = (decay) =>
new self.constructor(coordinates, vector, lifespan, decay);
this.build = () => Object.freeze({
coordinates: coordinates,
vector: vector,
lifespan: lifespan,
decay: decay
});
}
function MoveableBuilder(coordinates = [], vector = []) {
const self = this;
this.at = (...coordinates) => new self.constructor(coordinates, vector);
this.facing = (...vector) => new self.constructor(coordinates, vector);
this.build = () => Object.freeze({
coordinates: coordinates,
vector: vector
});
}
console.info(new MoveableBuilder().at(1,1).facing(2,1).build());
console.info(new ParticleBuilder().at(1, 1).build());
What I had trouble with is how to reuse the at and facing methods within the ParticleBuilder. Granted, since the signatures of both builders is different, it might not be the correct thing to do. However, I figured I could elicit the community for feedback on this.