proposal-deep-path-properties-for-record icon indicating copy to clipboard operation
proposal-deep-path-properties-for-record copied to clipboard

`alter` keyword

Open leontrolski opened this issue 4 years ago • 2 comments

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:

  • Easier to incrementally migrate existing code to contain mutations - you'd add a linting rule, then simply go around adding alter {} blocks where there were warnings.
  • For algorithm-y things it often seems like there is a "natural" mutation-y approach (see eg. any highly upvoted leetcode submission), these would still be permissible, just the scope of the mutation contained.
  • Advantage over immer would be the interpreter would be able to do structural sharing of eg. long arrays of numbers.
  • Not much new syntax.

leontrolski avatar Dec 15 '21 18:12 leontrolski

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?

hax avatar Jan 14 '22 16:01 hax

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.

leontrolski avatar Jan 31 '22 16:01 leontrolski