During the Math classes we learned how to define new operators. For example:
(ℝ, ∘), x ∘ y = x + 2y
This defines ∘
law. For any r
Read the comments below the answer.
Apparently you can't. Here is something close :
function exec(input) {
return Function(
'return ' + input.replace(/∘( *[\d.]+)/g, '+ 2 * $1') + ';'
)();
}
exec('2 ∘ 2'); // 6
No. JavaScript does not support operator overloading . but you can make a class method for doing this
var mathClass = function(value){
this.value = value;
}
mathClass.prototype.toLaw = function(){
return 2 * this.value;
}
var y = new mathClass(2)
2 + y.toLaw(); //2 + 2 * y
The short answer is no. ECMAScript (the standard JS is based on) does not support operator overloading.
As an aside, in ECMAScript 7, you'll be able to overload a subset of the standard operators when designing custom value types. Here is a slide deck by language creator and Mozilla CTO Brendan Eich about the subject. This won't allow arbitary operators, however, and the overloaded meaning will only be applied to value types. <- haha that ended up not happening.
It is possible to use third party tools like sweet.js to add custom operators though that'd require an extra compilation step.
I've answered with a solution from outside JavaScript using esprima - this is changing JavaScript and extending it, it's not native.
I was asking this question too, and here's my answer:
function myCustomOperation(string){
var res = String.fromCharCode(9762);
var thing = string.replace(/☢/g," + 10 + ");
thing=thing.replace(/☣/g," * 2 + ");
thing=thing.replace(/☠/g," / 3 * ");
return [eval(thing),string+" = "+eval(thing)];
};
var thing = myCustomOperation("
3 ☠ 4
");
document.write(thing[1]);
No. You can't do that in JS.
The closest you can have IMO is to implement your own object which has a chainable interface, aka "fluent" syntax. That way you can operate as if you were speaking out in sequence.
var eq = new YourEquationObject();
// Then operate like 1 - 2 * 3
eq.add(1).sub(2).mul(3);
Details are up to you though. Just giving out an idea.
The slightly longer then the short one is that Yes you can, but its a bit more involved then what you did in Math class
To extend the language with new constructs you can use a transformer like http://esprima.org/ or any of the others. You need to define your syntax, write the parser to parse your statement and finally add the actual code to do the math parts. When these parts is in place you have made a new language that works just as javascript but with the added support of the ∘
operator.
Its really not that hard to add new syntax, here is facebooks example how they add => arrow function syntax
https://github.com/facebook/jstransform/blob/master/visitors/es6-arrow-function-visitors.js