interface Array<T> {
x: number;
y: number;
sqrlen(): number;
len(): number;
normalize(): number[];
scale(s: number): number[];
add(b: number[]): number[];
sub(b: number[]): number[];
mul(b: number[]): number[];
div(b: number[]): number[];
dot(b: number[]): number;
cross(b: number[]): number;
}
Object.defineProperties(Array.prototype, {
'x':
{
get: function () { return this[0] },
set: function (v: number) { this[0] = v }
},
'y': {
get: function () { return this[1] },
set: function (v: number) { this[1] = v }
},
'sqrlen': {
value: function () {
let [x, y] = this;
return x * x + y * y;
}
},
'len': {
value: function () {
return Math.sqrt(this.sqrlen());
}
},
'scale': {
value: function (s: number) {
return [this.x * s, this.y * s];
}
},
'normalize': {
value: function () {
return this.scale(1 / this.len());
}
},
'add': {
value: function (b: number[]) {
return [this.x + b.x, this.y + b.y];
}
},
'sub': {
value: function (b: number[]) {
return [this.x - b.x, this.y - b.y];
}
},
'mul': {
value: function (b: number[]) {
return [this.x * b.x - this.y * b.y, this.x * b.y + b.x * this.y];
}
},
'div': {
value: function (b: number[]) {
let l = b.sqrlen();
return [this.dot(b) / l, b.cross(this) / l];
}
},
'dot': {
value: function (b: number[]) {
return this.x * b.x + this.y * b.y;
}
},
'cross': {
value: function (b: number[]) {
return this.x * b.y - this.y * b.x;
}
}
});
let a: number[] = [10, 20];
let c = a.add([20, 20]);
console.log(a.normalize(), a.x, a.y);