Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active October 17, 2019 11:22
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 rauschma/c00b747df893b8afa30bbdd0bb6357a9 to your computer and use it in GitHub Desktop.
Save rauschma/c00b747df893b8afa30bbdd0bb6357a9 to your computer and use it in GitHub Desktop.
class Point {
constructor(...args) {
switch (args.length) {
case 2: {
// Normal constructor
const [x, y] = args;
this.x = x;
this.y = y;
break;
}
case 1: {
// Copy constructor
const [other] = args;
this.x = other.x;
this.y = other.y;
break;
}
default:
throw new Error();
}
}
}
@jampy
Copy link

jampy commented Oct 17, 2019

both are valid and you could even provide both

The static variant has the advantage that it plays nice with other scenarios:

const foo = Point.fromOther(otherPoint) ;// aka copy
const foo = Point.fromLineStart(line); // conversion
const foo = Point.fromMidpoint([...geometries]);
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment