ecmascript-immutable-data-structures
ecmascript-immutable-data-structures copied to clipboard
All imutable data structures also need a subtraction operations
From what I can tell all the proposed types have extension operations defined but non of them have a subtraction, maybe syntax could be borrowed from elm ?
const point3d = {x: 1, y: 2, z: 17}
const point2d = {...point3d - z}
Can be done via destructuring and ES object rest/spread:
const point3d = {x: 1, y: 2, z: 17}
const {z, ...point2d} = point3d;
That doesn't allow you to remove something where you don't know the key ahead of time though. Though maybe you could use computed property names?
const {[key], ...newRecord} = record;
That's a lot more wonky than something this though:
const newRecord = record.remove(key);
I have perhaps a more radical idea. What about operator overloading?
+
// Concating lists
#[1, 2] + #[3, 4] === #[1, 2, 3, 4]
// extending objects/maps
#{a: 1, b: 2} + #{b: 3, c: 4} === #{a: 1, b: 3, c: 4}
This could be contentious, as the add operation is not commutative:
#{a: 1, b: 2} + #{b: 3, c: 4} !== #{b: 3, c: 4} + #{a: 1, b: 2}
But I think this is not a big deal. As Other operators, such as subtractions and division are not commutative anyway.
- Subtraction:
const point3d = #{x: 1, y: 2, z: 17}
const point2d = point3d - #{z}
I don't see any obvious use for the multiplication or division operators.
Would love for you to just think about it. It's possibly a very bad idea.
@nmn That could work together with Value Objects I guess.
After looking at some other ES7 proposals, it turns out that associative functions can be important. Specially for parallel operations.
So I think we're in a good place if we can support associative operators, even if they are not commutative. The + and - operators are both associative above. (I'll write a maths proof if that's needed) The only point of contention is the fact that many people assume that addition is always commutative but that is not case with records.
A possible way around would be to define the addition operation differently, and more like matrix addition. This would add the values of the same keys together. This would be a more correct way to do addition. But it would also be less useful due to typecasting.
Perhaps this could be best suited as some kind of function, a la Record.delete(#{ x: 1, y: 2, z: 3 }, 'z')
, which would then return a #{ x: 1, y: 2 }
. This allows for the ability to remove properties from a Record dynamically, while also allowing for compiler optimization if 'z' is literal.
Note: I'm also not opposed having a literal syntax that is equivalent to this.
We could simply hijack the delete
operator:
const point3d = #{ x: 1, y: 2, z: 3};
const point2d = delete point3d.z;
delete
is expected to return a boolean
nowadays.