Spherical forums

Creations => Programming => Topic started by: Radnen on October 27, 2015, 12:44:15 pm

Title: Operator Overloading in JS
Post by: Radnen on October 27, 2015, 12:44:15 pm
Guys, here's something neat I think some of you might find interesting. I was thinking of how I can overload operators in JS and was thinking about using the toString method, but if you use valueOf instead you can add some interesting logic to make operator overloads possible.

Pay attention to how the number 3 is used to figure out which operator was requested in the overload process.

Article: http://www.2ality.com/2011/12/fake-operator-overloading.html
GitHub Demo: https://github.com/rauschma/op_overload
Title: Re: Operator Overloading in JS
Post by: Fat Cerberus on October 27, 2015, 09:18:14 pm
This is a pretty neat trick, although I dislike operator overloading in general because it tends to be a very leaky abstraction.  For example, you can't do "abc" + "def" in C++, you have to cast at least one of the literals to a std::string.
Title: Re: Operator Overloading in JS
Post by: Flying Jester on October 28, 2015, 09:47:03 pm
Operator overloading is also very horrifically abused in C++. The io system in the C++ standard library is one of the worst examples of using operator overloading well, which is very unfortunate since it's most folks introduction to operator overloading in C++.

Nowadays I tend to just write my own io wrapper around C's io streams, using variable templates. It's just nicer to do in every way than C++'s standard library io.

One thing that has been long overdue is the new literal notation, which in C++14 will let you define a string literal as a std::string. Then you could do it without a cast. I like this compromise, since it means a string is just an array of chars normally, but can optionally be a std::string, if that's what you need. It's probably the only part of C++14 (or is it C++17?) I am excited for.
Title: Re: Operator Overloading in JS
Post by: Fat Cerberus on October 29, 2015, 05:50:45 pm
I guess the standards committee was trying to keep the language and standard library decoupled.  But that kind of thing is exactly what makes C# such a joy to work with--much of what it offers is just compiler magic around some feature or other of the .NET framework.  For example a 'using' block is just sugar for calling Dispose at the end (which is valuable--it saves a finally clause), and async/await is a very clean abstraction of threads and promises (or Tasks as .NET calls them).  In C++ the STL is completely auxiliary and feels at times more like a warty appendage than a proper compliment to the language.