jashkenas/coffeescript

Feature request around a = {b, c, d} = e

Closed this issue · 5 comments

(I realize work here is slow or stopped while @michaelficarra develops CoffeeScript Redux. It didn't seem like CS Redux was the place for feature requests just yet, so putting this here, but apologies if it should be elsewhere.)

I'm writing a REST API, and I'm finding that I commonly want to return subsets of objects. E.g. a user object might be {name, username, email, passwordHash, ...}, but I only want to return {name, username, ...}.

CoffeeScript's object destructuring is awesome, so I hoped this would work:

subset = {name, username, bio, url, numFollowers, numFollowing} = user

But instead, as expected currently, that sets subset to user. So I have to explicitly [de]structure over two separate statements, duplicating the props:

{name, username, bio, url, numFollowers, numFollowing} = user
subset = {name, username, bio, url, numFollowers, numFollowing}

So I wanted to ask if you guys would be open to extending the destructuring feature to allow sugar'ing this case too. a = {b, c, d} = e would set a to {b, c, d}, not e.

This would be a breaking change, but the good news is (a) I wouldn't expect this to be a common pattern in the wild, because/and (b) you can still achieve setting a to e by writing {b, c, d} = a = e.

What do you guys think? Thanks for the consideration!

Maybe not in that way.
Coco offers subdestructuring : a = b{c}

What you're looking for is Haskell's as-patterns. See my recommendation for inclusion in coffee-of-my-dreams. The value of assignment should always be the right operand. No breaking change needed.

Awesome. I'd be open to either syntax. =)

#2276

See also: #1617 #1708

Coco offers subdestructuring : a = b{c}

That's object slice. Subdestructuring is backward: b{c} = a

Thanks @satyr, #1617 / #1708 are exactly what I meant and want. Duplicates were tough to search for here not knowing the right vocabulary. Hoping to see this eventually!