Last active
October 17, 2019 11:22
-
-
Save rauschma/c00b747df893b8afa30bbdd0bb6357a9 to your computer and use it in GitHub Desktop.
This file contains 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
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(); | |
} | |
} | |
} |
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
What I don't know is which one is better: the instance approach (
clone()
) or the class approach (static clone(point3d)
). Although I prefer the instance approach, it's more concise, both in the definition and in the call, and the instance is always necessary.