tc39 / proposal-set-methods

Proposal for new Set methods in JS
https://tc39.github.io/proposal-set-methods/
Other
659 stars 15 forks source link

Infix versions of the set operations #77

Closed tintin10q closed 1 year ago

tintin10q commented 1 year ago

Python has this great infix shorthands for the set operations which are quite elegant. For instance, - 2 sets you get a new set with the difference.

The minus operator should be a nice and elegant shortcut for the .difference operator.

a = new Set([1, 2, 3])
b = new Set([2])
c = new Set([1, 3])

console.log(a - b) // Set({ 1, 3 })
console.log(b - a) // Set({ })
console.log(b - b) // Set({ })
console.log(a - c) // Set({ 2 })
console.log(c - a) // Set({ })
console.log(c - b) // Set({1, 3})
console.log(b - c) // Set({ 2 })

Example from the python docs

a = new Set('abracadabra')
console.log(a) // Set('a','b','r','a','c','a','d','a','b','r','a')

b = new Set('alacazam')
console.log(b) // Set('a,'l','a','c','a','z','a','m')

a - b                              // letters in a but not in b, difference
{'r', 'd', 'b'}

a | b                              // letters in a or b or both, union
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}

a & b                              // letters in both a and b, intersection
{'a', 'c'}

a ^ b                              // letters in a or b but not both, symmetric difference.
{'r', 'd', 'b', 'm', 'z', 'l'}

So - for difference, | for union, & for intersection and ^ for symmetric difference.

bakkot commented 1 year ago

I do enjoy this syntax in Python, but JavaScript, as yet, does not have operator overloading at all. And this proposal is not the place it will be introduced, if it ever is; that would be a separate proposal. You might wish to follow along at https://github.com/tc39/proposal-operator-overloading.