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

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

`alter` keyword #21

Open leontrolski opened 2 years ago

leontrolski commented 2 years ago

Looking at the examples, the immer approach is at the very least shorter, what about baking in the approach but with a new alter keyword?

const map1 = { a: 1, b: 2, c: 3 }
const map2 = alter (map1) {
    map1.b = 50
}
  • Everything we do to mutate map1 within the alter block applies only within the lexical scope of that block.
  • The block evaluates to the final value of map1 .

Some advantages would be:

hax commented 2 years ago

So map1 would be an mutable object which could collect the mutations, if I understand correct. It would be a much nicer syntax, but the problem is not sure how engines could optimized it.

And what happened alter (map1) { setTimeout(() => map1.b = 50) }? I supposed it should throw?

leontrolski commented 2 years ago

Sorry for the delay @hax! I'm not sure it would need to throw in that circumstance.

The await block would return whatever value map1 had immediately after running the code in the block, anything that is pushed to happen later in the event loop would just be ignored.

Considering an async variant is worthwhile though:

const map2 = async alter (map1) {
    map1.b = await someApiCall()
}

would suffice.