During the Math classes we learned how to define new operators. For example:
(ℝ, ∘), x ∘ y = x + 2y
This defines ∘
law. For any r
Set of compiled to JS languages support custom operators.
I would highlight ReasonML (ocaml-syntax-readable-by-js-folks) and Bucklescript (ocaml-to-js-compiler) which makes custom operators look neat:
For example an operator to concatenate strings can look like:
let (>|<) = (list, seperator) => Belt.List.reduce(list, "", (a, b) => a ++ seperator ++ b);
which can then be used like:
[Styles.button, Media.Classes.atLeastTablet] >|< " "
The downside of all this is the fact it has to be written in such compiled-to-js language, and it comes with lots of pros and cons, but usually those languages have the appeal of tons of nice syntactic sugar you don't get in js/ts
You can add pseudo-operators via methods on Number.prototype
:
Object.defineProperty(Number.prototype, 'myOp', {
value: function(that) {
return this + 2 * that;
}
});
Then all of this syntax will work
alert( (2).myOp(2) )
alert( 2 .myOp(2) )
alert( 2..myOp(2) )
alert( 2.0.myOp(2) )
2.myOp(2)
does not work because the period is treated as a decimal point
Given the somewhat new tagged template literals feature that was added in ES6 one can create custom DSLs to handle embedded expressions such as these including different algebraic symbols.
ex. (run in stackblitz)
function math(strings, x, y) {
// NOTE: Naive approach as demonstration
const operator = strings[1].replace(/\s/gi, "");
if (operator == "∘") {
return x + 2 * y;
}
else if (operator == "^") {
return Math.pow(x, y);
}
else {
return `Unknown operator '${operator}'`;
}
}
console.log(math`${2} ∘ ${2}`)
Note that since tagged template literals don't necessarily return strings as results they can return more complex intermediate AST like structures to build up an expression that can then be further refined and then interpreted while keeping close to the domain specific language at hand. I haven't found any existing library that does this yet for Javascript but it should be an interesting and quite approachable endeavor from what it appears from what I know of tagged template literals and usage in such places as lit-html.