Skip to content

Instantly share code, notes, and snippets.

@mikemaccana
Created December 17, 2019 16:58
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 mikemaccana/0ce93bad27431cd436a7ac54f962486d to your computer and use it in GitHub Desktop.
Save mikemaccana/0ce93bad27431cd436a7ac54f962486d to your computer and use it in GitHub Desktop.
// Stolen from https://github.com/rauschma/op_overload and ported to ES6
const log = console.log.bind(console)
var operands = []
class Point {
constructor(x, y) {
if (arguments.length === 0) {
x = 0
y = 0
} else if (arguments.length !== 2) {
throw new Error("Need either 0 or 2 arguments")
}
this.x = x
this.y = y
}
toString = function() {
return "Point(" + this.x + ", " + this.y + ")"
}
valueOf() {
operands.push(this)
// Lowest natural number x where the following are all different:
// x + x, x - x, x * x, x / x
return 3
}
equals = function(other) {
return this.x === other.x && this.y === other.y
}
set _(value) {
var operator
if (operands.length >= 2 && value === 3 * operands.length) {
// 3 + 3 + 3 + ...
operator = this.setAdd
} else {
throw new Error("Unsupported operation (code " + value + ")")
}
Point.operands = [] // reset
return operator.apply(this, operands)
}
setAdd(firstOperand) {
this.x = firstOperand.x
this.y = firstOperand.y
;[...arguments].slice(1).forEach(function(op) {
log(`op is ${op}`)
this.x += op.x
this.y += op.y
}, this)
return this
}
/**
* "" + mypoint won't invoke toString(), but valueOf().
* Work-around: "" + mypoint._
*/
get _() {
return this.toString()
}
}
var p = new Point()
p._ = new Point(1, 2) + new Point(3, 4) + new Point(5, 6)
log(p.toString()) // Point(9, 12)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment