tc39 / proposal-deep-path-properties-for-record

ECMAScript proposal for deep spread syntax for Records
93 stars 2 forks source link

Suggestions: Investigate `.{` operator for "mutations" #15

Open rbuckton opened 4 years ago

rbuckton commented 4 years ago

There was a strawperson many years ago for adding a .{ ("monocle mustache") operator for assigning multiple properties to an object that might be worth investigating. IIRC, the basic idea was this:

const obj = { a: 1, b: 2 };
obj.{ a: 3, c: 4 };
obj.a; // 3
obj.b; // 2
obj.c; // 4

This might be a useful operator to consider for replacing deep properties in records/tuples as opposed to, or in addition to, spread (...):

const rec1 = #{ a: 1, b: #[2] };
const rec2 = rec1.{ b[0]: 3 };
rec2.a; // 1
rec2.b; // [3]

The question would be whether .{ on a regular object would be mutating even if .{ on a record/tuple would not.

stiff commented 3 years ago

Rather than introducing weird overload for . operator, which accesses property, wouldn't it be better to overload + for objects/maps/sets/arrays?

This would lead to intuitive code:

obj + { a: 3, c: 4 }
obj = obj + { a: 3, c: 4 }
obj += { a: 3, c: 4 }
ljharb commented 3 years ago

@stiff no, that’s not possible, since it already has existing semantics. A new operator would be required.

stiff commented 3 years ago

New is ok, reusing existing with pretty much opposite function to previous is not.

ljharb commented 3 years ago

By "new" i mean "was a syntax error previously". .{ is new, + with objects is not.

stiff commented 3 years ago

Btw, the .{} and .[] are nice names for pick and values_at (props). Then update should be something like !{}.

hax commented 2 years ago

since it already has existing semantics.

@ljharb I think overloading + for tuple/record is possible, just like how we overload + for bigints. So #[1, 2] + #[3, 4] === #[1,2,3,4], #{a:1} + #{b:2} === #{a:1, b:2} could work. I'm not sure whether such overloading is good or bad, but I guess that we'd better throw TypeError for any + operation when operand is tuple/record for now, so we keep the overloading possibility in the future.