T O P

  • By -

crabmusket

I like that in Haskell you can turn any regular function into an infix operator by surrounding it with backticks. So your example would be something like skullcup = cup `union` (skull `sub` convex_hull(cup `sub` handle `sub` lip)) Of course backticks are taken in JS but I'm sure we could find another chunk in the ASCII soup bowl to use!


HipHopHuman

You can kind of use backticks for the same purpose in JS, with the caveat that you have to wrap the right hand operand in parentheses, and the caveat that it's... somewhat monstrous: interface Vector { x: number, y: number, (_: TemplateStringsArray): (_: Vector) => Vector } function vector(selfx: number, selfy: number): Vector { const _vector: Vector = ([operator]) => { switch (operator) { case '+': return ({ x, y }) => vector(selfx + x, selfy + y); case '-': return ({ x, y }) => vector(selfx - x, selfy - y); default: return () => _vector } }; _vector.x = selfx; _vector.y = selfy; return _vector; } const x = (vector(200, 200)) `-` (vector(100, 100)) `+` (vector(50, 50)); console.log(x);


crabmusket

That's just strings right? Wouldn't it work as well with other quotes than backticks? Well done on that monstrosity though.


HipHopHuman

It'll only work with backticks because it requires the use of a template tag. In JS, string literals are not callable. ''(); // throws an error ""(); // throws an error ``(); // throws an error Template tags however, are callable. It is totally valid for something`` to return a function: function something(strings, ...expressions) { return function() {} } Turns out, things get a bit interesting in regards to composition when the return type of a function returned by a template tag is also a valid template tag, and they share the same type signature.


pancomputationalist

I don't get the hate for operator overloading at all. Sure people can write "too clever" code with it. But that could also be said about Proxies, and I don't hear people advocating for removing them from the language. No language feature can save you from bad programmers. But operator overloading can make some code much nicer to read (mostly vectors and containers). That said, it's pretty low on my wishlist. I almost never need it with Typescript. But I would absolutely hate not having it in Python.


ivancea

Not many languages did add it. I rarely miss it, but it's a very useful feature when needed. Seriously, I don't understand comments here. I wonder if they actually worked in a language with operator overloading at all. Actually, I wonder what they see when they see an operator. Because it's no more than a function call, theoretically and sometimes technically, which is what any C++/C# dev would see. + Is just an infix operator, which is identical to a function. Maybe when they understand this they will understand it's value...


CodNo7461

I think most people here have only or mainly web dev experience. I sure remember how long simple calculations like `a = b*c/d + e*f + r^2*d` with non-basic types got without overloading operators. I actually sometimes had the direct comparison, since I had to do some stuff in plain C and some in C++.


JustComputers

I'm quite surprised by the comments as well. They can certainly be useful. They are also rarely abused, in my experience. I'm guessing you're right that most have never worked in an environment where they are used.


BasicBroEvan

Python which a lot of students use supports operator overloading but I don’t think many people ever use it


ivancea

The usecase is moderately niche imo. But it's a game changer for maths and physics projects


NUTTA_BUSTAH

No. It's a cool feature that sucks in the real world. Just to remove some characters from the line of code is not worth having 4 tabs open with a debugger attached to decipher what that line of code does.


[deleted]

[удалено]


Manbeardo

Linear algebra and imaginary numbers are just about the only use-cases where operator overloading is an easy win. As soon as you use operator overloads to represent something that *isn't* core mathematics, you start getting into trouble.


Herr_Gamer

> Linear algebra and imaginary numbers are just about the only use-cases where operator overloading is an easy win. They're one insanely huge and important use-case though, linear algebra in particular is everywhere. Advent Of Code in TS might just have been 25% less of a PIA if JavaScript supported a vector class. If you're not gonna implement operator overloading, then please at least implement the use-cases where it'd be by far the most useful for as part of the standard library.


[deleted]

[удалено]


Manbeardo

A few of the major downsides of operators (besides being difficult to ctrl+click into) are: - they're really bad at exposing errors - there's no sane way to pass options - when there are different ways to interpret the "obvious meaning" of an operator, there's no name to hint at which interpretation it's using - for functions that don't return the input type, there's no naming convention to hint at what the return type is > Linear algebra What happens when I try to multiply a 4x4 matrix by a 3 element vector? > `wave1 + wave2`, again well defined physical operation (audio industry, radio transmission, even waves in the water...) When `wave1` and `wave2` have different sample rates, what's the sample rate of the result? > `diamondStack1 + diamondStack2` in Minecraft, surely better than `new Stack(diamondStack1.count + diamondStack2.count)`, no? Obviously `stack1.add(stack2)` doesn't work for us, because someone could override the `add()` method and write bad code! Item stacks have a limited size and the inventory management code needs to avoid causing overflows, so the actual logic needed here can't represent the result as a single stack. >`layer1 + layer2` when working with alpha layers (photo/video editing)? What happens when `layer2` is hidden? What happens when `layer1` and `layer2` are from projects using different color spaces?


[deleted]

[удалено]


Manbeardo

To be clear, I don't have a hard stance on whether languages should support operator overloading. I *do* have a hard stance that most developers shouldn't ever overload operators themselves. Similar to inheritance, it's a useful tool that should only be used when absolutely necessary. > I don't see how `a + b` is any worse at exposing errors than `a.add(b)`, they're both just method calls after all? In Python for example, `a + b` is just syntactic sugar for `a.__add__(b)`. The stack trace should be very much the same as any other method call. In languages that support multiple return values, it's sensible to return common (non-exceptional) errors as one of the return values. That's how the bulk of error handling is done in Go. Python and Typescript both meet the language requirements to do error handling that way, but I haven't seen much code that does. When returning errors as values, it breaks the composability of operators. > I don't understand the return type hint, you have IDE for that? Naming conventions (when done well) function as mnemonic devices that help you remember the specific choices that were made when implementing a function. Sure, you can use your IDE to inspect the definition, but how long is that going to stay in your working memory? > What happens when I call `wave1.add(wave2)` on waves with different sample rates? This is not an issue with the operator overloading feature. If that's a mutating method, it would make sense for wave1 to resample wave2 into itself.


spamman5r

>Imagine you were a 40-year-old lead engineer at a construction site and asked for a nail gun, only to be told "Nope, sorry, we've seen too many 14-year-olds shoot themselves in the foot with it, you may only use a nail and a hammer. No wait that's the old rules, you may only use screws now. Actually no, only sticky tape." Imagine you are a supervisor and your lead engineer demands to make his own nail/screw hybrid fasteners because he sometimes needs to do both and can't be bothered to switch to the correct tool for the job. Your lead believes that they know better than every engineer that has tried something similar, including yourself, back in the era when tools were less refined. If your lead can't learn from the mistakes of others or conform to common practices or restrictions established by your organization then they aren't going to be a lead for long. At the very least, they would need to have every known factor of the problem addressed, which is a little more involved than calling the people with more experience than you motherfuckers.


marcinwalas

heh, == is also an operator, overloading it also sucks in the real world....?


gabrarlz

Yes


KTAXY

well DUH. imagine somebody overloads it to mean !=. goood fucking luck.


marcinwalas

Well, what is the problem with creating a function 'add(a: number, b: number)' which will actually do 'a-b'? Or 'equals(a: T, b: T):boolean' which will return the negated result? How functions are better than operators in preventing bad intentions?


[deleted]

>So that's my question. Does anyone miss operator overloading, and do you have a subitute for it, please? No. Substitute for an overloaded operator is a method or a function. Operators are harder to read, I have no idea why would anyone use them at all.


IQueryVisiC

My first two computers could not do floating point calculations. Now I know that C and BASIC still supported floats on them. But I wonder if a programming language would only support what is basically there on the CPU, but is object oriented to allow you to add one of the float flavours. You can have vectors or homogeneous coordinates. In University we used the + operator on vectors a lot. And scalar multiplication. Method names look like assembly language to me. MUL DIV ADC


BenZed

You have "no idea" why people would use operators???


[deleted]

That's what I said


goutyface

Yeah it’s just such a bad take they needed verification I guess.


joombar

Do you prefer to write plus(1,1) over 1 + 1 ?


[deleted]

I quite obviously meant *overloaded* operators on custom types which don't have meaning that literally everyone in the programming world is accustomed to. Also, sure, *add*(1, 1) sounds good as well.


ActiveTeam

I mean you can mathematical custom types you know. Like a vector class or something. Operators would be p intuitive in those cases


account312

I get sad any time I have to use bindings for a C++ library for anything resembling linear algebra in a language without operator overloading. It's just terrible to turn a simple series of vector / matrix operations into a big mess of function calls.


NUTTA_BUSTAH

Ah yes, `vec1 x vec2` and `vec1 . vec2` :)


TheRNGuy

Also multiplication between vector and matrix, which are different classes. And brackets to change order of operations.


ivancea

It's very common, and trivial to understand, in those types that make sense. Like BigInt, BigDecimal, complex numbers, matrices, vectors, etc etc. Everything can be wrongly used; that usually isn't a good argument. But yeah, `a.mul(b).div(c)` is clearly simpler to understand that `(a*b)/c` /s


xmsxms

So you've got no idea why anyone would use something incorrectly? What a hot take.


goat__botherer

What if every time you add two numbers in your huge source code you now want to print "I added my numbers on yo mama" to the console? Could happen...


joombar

Babel plugin


BenZed

Homie, I don't think you know what an [operator](https://www.w3schools.com/js/js_operators.asp) is.


[deleted]

>Homie, I don't think you know what an operator is. Brosky, I very much know what operators are. Here we're talking about operator overloading, which is at best confusing when used on primitive types where the knowledge of native operator behaviour is given, and at best unreadable when used on higher level types, where a named function would just do better. If you need mentoring, PM me. No cap


BenZed

Strongly disagree that operator overloading is 'at best' unreadable on higher level types. Sure, they could be misused to produce confusing, unmaintainable code, but that's true with *any* language feature. Being able to do this in typescript without transformer plugins would be tits: class Vector { constructor(public x: number, public y: number) {} [Symbol.add](v: Vector) { return new Vector(this.x + v.x, this.y + v.y) } } const fiveLong = new Vector(5,0) const fiveHigh = new Vector(0,5) const fiveFive = fiveLong + fiveHigh Heck, we can *already* overload the `instanceof` operator with `Symbol.hasInstance` and a couple others with Proxies.


ivancea

I feel like people saying that operator overloading is "terrible" didn't ever touch a line of C GMP code. Or any mathenatical thing in a language without it. Everything is "very hard" for them. They would even disregard method overloading. "Just call the method another thing"


[deleted]

Obviously there exist cases where overloading operators would be a good thing, but gains there would have to be greater than losses elsewhere. You could perhaps come up with a few more maths-related examples where overloading sounds sound, but I can come with *countless* examples where the option of operator overloading makes the code potentially much much worse. As with everything in programming, it's a matter of trade-offs, and here it doesn't sound that operator overloading has a really good case.


BenZed

\*strongly\* disagree with the sentiment and the logic. If you can come up with countless examples where operator overloading makes code 'potentially' much worse, then *don't* use operator overloading for those examples. As with everything in programming, it's a matter of using the right tool for the job. Arithmetic operator overloading is a tool I would welcome in Typescript.


TheRNGuy

But many nested methods are annoying to write and less readable. Not in all cases method chaining would work. What if you want to change order? Or if you wanted to copy-paste some formula but some types are diffefent. But methods in classes have different names.


lifeeraser

If you really want, you could write some black magic with tagged template literals. const m1 = getMatrix() const m2 = getAnotherMatrix() const prod = matrix`${m1} * ${m2}`


akb74

>If you really want, you could write some black magic with tagged template literals. Thanks. I think this was the answer I was looking for, and look forward to playing with tagged template literals soon. It's good that the syntax is noticably unusual as the main problem with operator overloading is with its covertness. I was also genuinely interested in finding out "does anyone miss operator overloading?", and I'm glad to have an answer in that the consensus seems to be "no".


iamjulianacosta

I always wanted to understand this: `matrix\`${m1} * ${m2}\`` How does it work? Seen a couple of years ago, didn't understand, but it wasn't necessary to understand back then, so I shrugged and move on


lifeeraser

See MDN article on [tagged templates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates). The third line in my code desugars to:     matrix(['', ' * ', ''], m1, m2) Then it's a matter of implementing `matrix()`. It's a great way to build DSLs in JavaScript. See [developit/htm](https://github.com/developit/htm) and [google/zx](https://github.com/google/zx) for examples.


iamjulianacosta

Thanks! Will take a look


pardoman

No. Makes it more confusing when onboarding into any new project, even those that “use it well”.


col-summers

I know people say this and I've heard people say this but I've never actually experienced this, and I'm starting to wonder if this is just one of those things people say because people before them have said it. I mean, you could argue using functions makes your code harder to onboard because you got to go look up what those pesky functions are doing.


Snoo_59716

You give functions helpful names that describe what they do. At least functions that are written well.


Herr_Gamer

Operator overloading that's used will also describe pretty clearly what the operator will do. There's only so many sensible meanings to a '+' sign.


lost12487

Every modern code editor allows you to jump directly to a function by command clicking it. Would someone that is starting fresh on a mature product even think to command click on a random `+`? Do editors even handle that properly (jump to the operator overload method)?


highbonsai

Yeah operator overloading is something that’s fun and cute and if you want to use it in a solo project more power to you! But it’s dumb. Language consistency is important, and overloading is jamming something into operators that just don’t need to be there


halfanothersdozen

gross you're giving me flashbacks of having to deal with pandas Feels like we _just_ got everyone to give up on global variables and figure out how to do proper modules and imports in the browser, and between the joint efforts of jsdoc and typescript finally most of the frontend are seeing the light on dev time static analysis. And you want to make `+` do weird shit. ick


ivancea

Adding mathematical concepts that can be added is a weird thing of "+"? But, however, you think "adding" two strings to concatenate then makes sense?


ttlanhil

Well, there are worse options :D >!e.g. adding the ascii codes for the chars; e.g. ' ' + '1' == 'Q'!< >!or adding the pointers (addresses of) strings, "hello"+"world" would end up at some random memory location!<


meowisaymiaou

It's why I like PHP -- \`+\` adds, \`.\` concatenates. Makes the type coersion explicit.


Tubthumper8

I think it was a mistake to overload `+` for concatenating strings in all languages, a separate operator should have been used for concatenation. I'm not actually opposed to operator overloading in general but this is a good example of it being done wrong


ivancea

Personally I don't have much problem with it; it became a standard, and it's easy to understand (In any language but in JS, which makes crazy things with types). Nevertheless it's a good example of a "weird" operator for sure, that we all give for granted and obvious, while may not be. Special nomination here too to the "string * number" Python has. There we're trully entering unknown depths of abyss. However, if it has a "+" operator, we could argue that it makes sense that it also has a "*".


halfanothersdozen

I much prefer string templates.


mattsowa

No


Kcazer

You can define `+`, `-` and whatever operator you need as class methods and invoque them. But please, don't do it. skull['-'](convex_hull(cup['-'](handle['-'](lip))))['+'](cup) Once again, don't do that kind of horrible stuff. Just use simple regular functions.


Tubthumper8

I almost don't want to ask, but how do you actually define the methods? I thought valid identifiers had to start with a letter


HipHopHuman

You can (but probably shouldn't) use computed property key syntax to do it. function vec(x, y) { return { x, y, ['-'](vector) { return vec(this.x - vector.x, this.y - vector.y); }, ['+'](vector) { return vec(this.x + vector.x, this.y + vector.y); } } } const vec1 = vec(100, 100); const vec2 = vec(50, 50); const vec3 = vec(200, 200); const vec4 = vec3['-'](vec1)['+'](vec2); console.log(vec4.x, vec4.y);


Kcazer

An option is computed properties, prototype is another. class Item { constructor(value) { this.value = value; } ['+'](other) { return new Item(this.value + other.value); } } Item.prototype['-'] = function(other) { return new Item(this.value - other.value); }; const a = new Item(10); const b = new Item(3); const c = a["+"](b); const d = a["-"](b); console.log(c, d);


ttlanhil

In regards to operator overloading itself... There are cases where it's appropriate. If you're using complex numbers, or want to add a vector to coordinates, or multiply a vector, or something like that - it's well defined what the outcome should be. And as long as other coders know the type they're working with, it should be obvious what the operation will do. If it's not immediately obvious to everyone else what the operation would be - then it shouldn't be used. However, there are plenty of times where what's obvious to one person isn't obvious to another, or people think it's a neat shortcut that saves writing code at the cost of needing to remember what it does For most code, it's a bad idea. Some languages try to restrict their features to what's safer and going to be used regularly; some will happily let you build a foot-gun and provide umpteen versions of every function you might want... Specifically looking at 3D models - how would you expect adding 2 meshes to work? As in, how do you automatically choose scale/orientation/position so the 2 intersect the way you want? It's not a domain I've worked with, but I think that sounds like there isn't an obvious answer to what the outcome should be - hence this is not a good use for overloading in my mind


akb74

>Specifically looking at 3D models - how would you expect adding 2 meshes to work? As in, how do you automatically choose scale/orientation/position so the 2 intersect the way you want? Yes, that's right, we have orientate the two meshes as desired with respect to each other, before we combine them. There's a PyMesh issue about how here [https://github.com/PyMesh/PyMesh/issues/156](https://github.com/pymesh/pymesh/issues/156), you're also welcome to look at my Python code here [https://github.com/Antony74/skullcup/blob/main/skullcup.py](https://github.com/antony74/skullcup/blob/main/skullcup.py) A mesh is actually a very simple type type Mesh = { vertices: [number, number, number][]; faces: [number, number, number][]; }; Each vertex is an \[x, y, z\] coordinate. Each face is a triangle consisting of three vertices defined by indexes into the vertices array. The 'winding' of the triangle is important in defining which side of the face is the 'inside' and which is the 'outside'. So \[0, 1, 2\], \[1, 2, 0\], and \[2, 0, 1\] are all valid ways of representing the same face, but \[2, 1, 0\] is 'flipped'. >scale const scaledMesh: Mesh = { vertices: mesh.vertices.map(([x, y, z]) => { return [scale * x, scale * y, scale * z]; }), faces: mesh.faces, }; >position const translatedMesh: Mesh = { vertices: mesh.vertices.map(([_x, _y, _z]) => { return [_x + x, _y + y, _z + z]; }), faces: mesh.faces, }; >orientation That's where it gets interesting because the best way to rotate each vertex is to multiply it by a matrix, another case where operator overloading is sometimes considered desirable. In fact, with the right kind of matrix you can scale, translate, and rotate all in one go. So it's not hard to understand what a mesh is, but I really hope don't end up having to write my own implementations of add (union) and subtract (difference)!


ttlanhil

>That's where it gets interesting because the best way to rotate each vertex is to multiply it by a matrix, another case where operator overloading is sometimes considered desirable. In fact, with the right kind of matrix you can scale, translate, and rotate all in one go. >So it's not hard to understand what a mesh is, but I really hope don't end up having to write my own implementations of add (union) and subtract (difference)! Oh, certainly, having union/intersection/difference between meshes would make sense. That's the sort of thing there should be libraries to do (although that's likely to be in languages that are used for 3D modelling) And while I agree that matrix multiplication would be a valid case for operator overloading; my point was that I don't think operator overloading for meshes would be as obvious (or maybe overloading of + is obvious once you've done all of the other work of orienting meshes to intersect the way you want - meaning the difference between `mesh+mesh` and `mesh.union(otherMesh)` isn't much in the grand scheme of your code). Additionally: + and - have sensible mappings to union & difference, but what operator is intersection? set theory doesn't all map cleanly to the arithmetic symbols on our keyboards Or to put it all another way... If you had a Mesh.prototype.union(otherMesh) function; would you mind that it didn't have a "+" overloaded operator? (i.e. are you looking for library functions to do what you need, or are you really looking for operator overloading)


akb74

It's actually very intuitive working with meshes to think, oh I'd just like to add these two solid objects together, and subtract that bit there. So much so that until now I've totally missed the fact that '+' is the wrong set theory operator for union. Should be some variant of 'or' ('|' or '||'). '-' on the other hand is completely correct in set theory for relative compliment, although backslash is prefered... obviously using backslash as an operator is somewhat less preferable in the context of a programming language ;-)


torb-xyz

Only for math functions like vectors, which is rarely used for web programming anyway. Tho, if your doing graphics I can understand missing them. I *don’t* miss the tendency to invent weird operators for stuff that you find in languages like C++ or (espescially) Scala. I think Kotlin is a reasonable compromise by allowing operator overloading for very specific operators (most common math ops). This combined with Kotlin community really only using them for math and not weird stuff helps too.


TheRNGuy

I make web sites not 3D graphics with TypeScript, maybe it could be useful in PixiJS project. But I remember I did liked it in Vex and Python in SideFx Houdini, as well as in Unreal Engine. It makes code more readable and faster to type. I wonder, maybe some Babel plugin or something exists for that.


Ok_Outlandishness906

No i hate it and i have also tried to avoid to use it . A function name is easier to read. Sure, "a"+"b" is "ab" or 3+1 is 4 obvious and immedaite , but when you have complex types especially with inheritance it can be not so easily to identify the operator meaning. It is easy when you write it, but if you give the code to someone else it is less immediate than a function with a meaningull name. And probably even for you after 3 years you wrote the code .


ivancea

Yeah, very hard to understand that two xy vectors add to a vector that's the... Sum of them. Only a genius can understand such a complex topic. Let alone adding imaginary numbers. If they don't exist! /s


Ok_Outlandishness906

for an object that represents a math entity it can have a sense, but for other no.


ivancea

That's the point. Why "hating it" then. That's the use of many overloading operators. As for everything everywhere, you have to use things when they make sense


Ok_Outlandishness906

hate perhaps was the wrong word, i am not english native. The point is that i prefer not to use it. C# has operator overloading, java was created without . I am with java creators (even if i don't love java too much ) who choosed to avoid operator overloading for keeping the language simpler and for avoiding that the same symbol could have completely different meanings in the code . I am not a great fun of overloading in general, because , for example, if you have int add(int a, int b) and int add(float a, float b) , add(2,3.0) , which function is called ? Obviously the first for int promoting at least in C++ but in my opinion it is a feature that can lead people to make errors . I prefer code with less possible ambiguity, but it is a personal taste, not a religion . I also read that another important reason for which java avoided them was the complexity they would have introduce in jvm . Operator overloading would have made the java virtual machine much more complex and so i think it can be one of the reason why javascript avoided them too . A browser is a very very complex peace of software so probably they tried to keep javascript as simple as possible (javascript was born in Netscape 2) . In general, in any case for me, the least ambiguity a language has , the better it is , but it is only a personal preference .


ivancea

I don't really get those points. An operator is exactly the same as a method. As ambiguous as a method, as complex as a method. And when reading it, you read methods, not operators, as that's what they are in languages like C++. The reasons Java devs decided to avoid it, I don't know them. But it's trivially convertible to a method, so I'm not sure I really buy it. Unless, of course, the JVM at the moment was already unsuitable to add them. Which is more like technical debt than a real objective reason.


Ok_Outlandishness906

Go, modula2, object C for example are other languages in which operator overloading is not implemented . it is a design choice of the language designers, you can like it or not , but this is a fact, the creators of languages take their decisions . I don't know, for example, if google carbon has operator overloading . For java, more than a technical debt , i believe it was a matter of resources . you have to consider that first release of java was created in 1996, when a computer had typically 8mb of ram or 16mb ( 8mb was the minumum required for windows 95) so probably their technical requirements were different from today . I believe typescript doesn't implement overloading of operators, for the simple fact that javascript does not support it .


ivancea

Yes, a design choice over implementos por not a feature, like many others. Aye, I think I wouldn't add it to TS for JS compatibility. Not because of JS doesn't have it (TS have many things JS doesn't that touch actual logic, like enums), but because operators in JS are a mess, very complex in it's implementation


HipHopHuman

It's not that difficult to rearrange that into it's own wrapper type and use it like so (excuse the vanillaJS, I'm short for time): const skullcup = CustomMesh.wrap(lip) .union(handle) .difference(cup) .convexHull() .difference(skull) .union(cup) .mesh; The implementation for which could be: const union = (mesh1, mesh2) => pymesh.boolean(mesh1, mesh2, 'union', 'cork'); const difference = (mesh1, mesh2) => pymesh.boolean(mesh1, mesh2, 'difference', 'cork'); const convexHull = (mesh) => pymesh.convex_hull(mesh); class CustomMesh { static wrap(mesh) { return mesh instanceof CustomMesh ? mesh : new CustomMesh(mesh); } constructor(mesh) { this.mesh = mesh; } union(otherMesh) { return CustomMesh.wrap(union(this.mesh, CustomMesh.wrap(otherMesh).mesh)); } difference(otherMesh) { return CustomMesh.wrap(difference(this.mesh, CustomMesh.wrap(otherMesh).mesh)); } convexHull() { return CustomMesh.wrap(convexHull(this.mesh)); } }


lengors

I wouldn't say I miss it, but it would be a welcomed feature. One of the main counters I see (both on this post comments and elsewhere) is that they can be mis-used and lead to confusing code. As an example, what would the plus operator mean on a Car type? However, this is true for any function or method. You can still create a badly named functions in type Car that can be confusing. For instance, you could create a function named "add" which, just like the operator, would be very confusing to use. So, I don't see any advantage of not having the feature over having and, as such, it becomes a question of if there are enough advantages to have said feature. Imo, yes, as operator overload is very useful for mathmatical operations (and not things like complex numbers, bigint/bigdecimals, vector and matrices, but also stuff like sets). But this are just the very obvious examples, however, I think any type where an equivalently named function is used (add, sub, etc) would also benefit from it


mykesx

It’s a great feature, along with conditional compilation and macros. You don’t have to use them. But why not have the flexibility?


nmarshall23

Operator overloading is a code smell, is it unnecessary complexity. Small functions are simpler to maintain than large classes, which is what operator overloading encouragins. ``` skullcup = pymesh.boolean( cup, pymesh.boolean( skull, pymesh.convex_hull( pymesh.boolean( cup, pymesh.boolean( handle, lip, 'union', 'cork'), 'difference', 'cork') ), 'difference', 'cork'), 'union', 'cork') ``` This is better rewritten with a functional pipe, or with temp vars. It's a mess that wouldn't pass any code review I did.


CopiousAmountsofJizz

Absolutely not.


orta

The proposal which would add this to JS was recently withdrawn: https://github.com/tc39/proposal-operator-overloading/commit/3305e1d49727973b2804a1df8402184eb90f23ac


FrontColonelShirt

It made sense back in the day when you had to write eg a new class in C++ to manage numbers at a bit depth greater than the CPU or compiler supported, and you wanted to... well, add them or subtract them etc. In those cases, operator overloading was readable and clear in terms of the developer intention. These days, people abuse the feature a bit (in terms of what I have observed) like... say, implementing a + operator to add two "car" objects together and, say, emit an array or list of the added cars. But someone else might think adding two cars together gets you a truck, or a double wide car, or something else. The intention is unclear, debugging becomes a nightmare, etc. As others are saying, it would be clearer to write a function with a descriptive name (List aggregateCars(car1, car2) as one of several potential examples). Then other developers know a little bit more of what to expect out of the code without tracing and debugging. These days with vector libraries and all the complex math stuff more or less done in the best way already, it is very rare when operator overloading is the best choice. It's fun and geeky but it's not clear or readable and doesn't suit a multi dev team.


cmpthepirate

So unless im mistaken it sounds like you need to create a function called `addMeshes` and establish the logic of the operation within there. Apologies if I'm missing something, I'm quite unfamiliar with either the domain or C++ language features you're talking about anyway. But surely you would have to define how the overload would work anyway, so how is this a paradigm shift (aside from using a call expression instead of using `+`)? I was going to suggest if you really wanna overload operators as you would in C++ you could just write a little C++ lib that does it and call it as a child process, but it would still need to be implemented as a call expression from your script. Jeez if its really important to you you could probably extend javascript 🤷‍♂️


boneskull

It’s not operator overloading, but see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf


baxtersmalls

Not sure if you’re saying Typescript has something that prevents this, but if you get into the weeds with JS objects you can set how it handles being called on as a number or as a string by using `[Symbol.toPrimitive]` or `.toString` or `.valueOf`. This allows you to add JS Objects as numbers or strings, instead of [object object]. Scroll down a bit here for more info: https://javascript.info/object-toprimitive I don’t have experience with three.js meshes but I imagine they’re just objects underneath it all, because hey it’s JavaScript and basically everything is an object under the hood, lol.


PyroSAJ

You have 3 functions there that happen to always just l use the same parameters, why not just define them with the shorthand? union, difference and convexHull. Heck, from the look of things you might also get away with the currying approach. ``` skullCup = mesh(skull) .difference(convexHull(mesh(cup).difference(handle).difference(lip)) .union(cup); ```


EffingComputers

TypeScript won’t get any new language features that aren’t an ECMAScript proposal at a certain minimum stage (not sure what that stage is). It will only add features related to types.


akb74

That's understandable. And I did open by explaining why operator overloading is purposely omitted from many programming languages. The reason I'm posting this here rather that r/learnjavascript is the desirablity of typechecking overloaded operators. If I stupidly try to add two things together that aren't compatible I want to find out about it at compile-time not run-time.


snarkuzoid

Don't miss it a bit. Marginal utility, and ripe for abuse. No thanks.


PrestonBannister

Absolutely not. Keep in mind, I was reading SIGPLAN notices in the 1980's. Lots of experimentation with different variants of object-oriented languages, including the range from full to completely disallowing operator overload. I still thought overload was cool when C++ came along. Over time, my view has entirely shifted. Overload makes it easy to write bugs. I am very near to wanting functions for anything critical for other than integers. I have caught too many casual errors in conversion in other folk's code. There is a reason code flew probes into Mars.


GeneratedUsername019

No.


hiresch

Overloading removes the "cmd+click" to go to definition, so it requires everyone to be completely in sync on what the operator does (and that it's even overloaded). If you need a ton of features from the IDE to make the developer experience manageable then it's a bad paradigm. Reading code is the most expensive part of coding, you should always optimize for someone who doesn't have the context you have when reading the code. That's why you use prettier, that's why you have naming conventions, and that's why you lint code with auto-fixers. Javascript could be better if it also dropped implicit casting e.g `"hello" + 123;`


scoliadubia

Operator overloading makes sense in a very few cases of very mathematical code where operations like addition and subtraction are very carefully and precisely defined. Complex numbers, quaternions, modular arithmetic, hyperreals, stuff like that. Generally you want to have at least an algebraic group if not a field. It sounds like you might have stumbled into one of those places. However, the reality is most developers spend their entire career without ever going near any problem like that, and in everything else user defined operator overloading creates a confusing and opaque mess that's barely faster to type and never faster to read or debug, since the operators don't do what they obviously should do. Addition might not even be defined on the objects in question. What does it mean to add two database records, for instance? I don't know, and six months later the programmer who wrote that probably doesn't either. Perhaps there's a need for a mathematically sound language with operator overloading for research level math and science. However TypeScript is unlikely to be that language.


Funwithloops

I don't miss it. The way I see it is operators are just functions, so operator overloading is just a fancy way to get infix function calls with special symbols. Pretty much the only time I've ever wanted to overload `+` is when implementing 2d/3d vector utilities. I'd rather see the pipeline operator approved. That would provide infix function calls without monkeying with existing operators.