JSFiddle - React, Tailwind, and code Playground
by Alexander
JavaScript
console.clear();
class Vector extends Array {
constructor(...args) {
super()
this.push(...args);
}
valueOf() {
if (!Array.isArray(Vector.operands)) Vector.operands = [];
Vector.operands.push(this);
return 3;
}
_add(...args) {
args.forEach(a => this.push(...a) );
return this
}
sum(a, b){ return a + b }
subtract(a, b){ return a - b }
multiply(a, b){ return a * b }
divide(a, b){ return a / b }
operate(fn, a, b){
if(a.length!==b.length)
throw new Error('Cannot operate arrays of different lengths');
return b.map((b, i) => fn(a[i], b))
}
calculate(...args) {
var f = args.shift();
this.push(...this.operate(f, ...args));
return this
}
toString() { return `Vector(${this})` }
get calc() { return this.toString() }
set calc(v){
var ops = Vector.operands, operator;
//console.log(value);
//console.log(ops.length);
switch (true) {
case (ops.length === 2 && 3 * ops.length === v):
operator = this.sum;
break;
case (ops.length === 2 && 1 === v):
operator = this.divide;
break;
case (ops.length === 2 && 0 === v):
operator = this.subtract;
break;
case (ops.length === 2 && (3 ** ops.length === v)):
operator = this.multiply;
break;
default:
throw new Error('Unsupported mixed operation with more than 2 operands');
}
Vector.operands = [];
this.length = 0;
//return operator.apply(this, ops);
return this.calculate.apply(this, [operator, ...ops]);
}
}
let p0 = new Vector(0);
let p1 = new Vector(1,2,3);
let p2 = new Vector(4,5,6);
let p3 = new Vector(7,8,9);
p0.calc = p1 + p2;
console.log(p0);
p0.calc = p1 - p2;
console.log(p0);
p0.calc = p1 * p2;
console.log(p0);
p0.calc = p1 / p2;
console.log(p0);