Vector/point javascript fake operator overloading
by microbians
HTML
<html>
<body>
<div>
<h2>POINT.js v2 – microbians.com</h2>
Create a point object and this function operations with Fake point operator ovreloading (Look at the console for some info)<br/>
<br/>
v2 - added cross " ˣ " and dot " · " product fake operators<br/><br/>
</div>
<hr/>
<div id="w"></div>
<div id="h"></div>
<hr/><br/>
<div id="r"></div>
<br/><br/>
Other ways to used can be
<textarea style="width:90%;height:22em;">
var w = new point(100,200);
var h = new point(20,30);
// FUNCTION FORMAT Arrow and Function
// Can't use spaces between cross or dot product simbols in "function" format
var p1 = new point(()=>{ h / wˣh + 2 }, {w,h});
var p2 = new point(function(){w + h * 1000 + h}, {w,h});
// STRING FORMAT
// Here is fine to use spaces between cross or dot product simbols in "string" format
var p3 = new point("( w ˣ h + w · h ) * h", {w,h});
</textarea>
</body>
</html>
CSS
body {
background: black;
color: white;
font-family: sans-serif;
}
JavaScript
/********************************************************
POINT.js – microbians.com
Create a point object and this function operations
with Fake point operator ovreloading
********************************************************/
class point {
constructor(x,y) {
if (x != undefined) {
if (x instanceof Array) { // In case created from and array new point([0,0])
this.x = x[0];
this.y = x[1];
} else if (x.constructor.name == "point") { // In case created from object point format new point({x:0,y:0})
this.x = x.x;
this.y = x.y;
} else if (typeof x == "string" || typeof x == "function"){
let formulaArgs = [];
let formulaVals = [];
let formulaValsX = [];
let formulaValsY = [];
for (let name in y) {
let value = y[name];
formulaArgs.push("_"+name);
formulaVals.push(value);
formulaValsX.push('let '+name+'=_'+name+'.x;' )
formulaValsY.push('let '+name+'=_'+name+'.y;' )
}
formulaArgs = "\""+formulaArgs+"\"";
formulaValsX = formulaValsX.join("");
formulaValsY = formulaValsY.join("");
let formula = (typeof x == "string") ? x.split(" ").join("") : x.toString().split(" ").join("").split("()=>{").join("").split("function(){").join("").split("}")[0];
console.log('Cleaned original forumla → '+formula);
// Dot Product -> this.x*p.x + this.y*p.y
formula = formula.replace( /([a-zA-Z0-9_-]{1,})\·([a-zA-Z0-9_-]{1,})/g, "(_$1.x*_$2.x+_$1.y*_$2.y)");
// Cross product -> this.x*p.y - this.y*p.x;
formula = formula.replace( /([a-zA-Z0-9_-]{1,})\ˣ([a-zA-Z0-9_-]{1,})/g, "(_$1.x*_$2.y-_$1.y*_$2.x)");
console.log('Dot or Cross product added → '+formula);
let functionX = 'return new Function('+formulaArgs+',"'+formulaValsX+'return '+formula+'").call({},'+formulaVals+')';
let functionY = 'return new Function('+formulaArgs+',"'+formulaValsY+'return '+formula+'").call({},'+formulaVals+')';
console.log('Generated Function for X Value →...