Proposal: `&` operator as shorthand for items in iterations

Hi Everyone,

This is one usecase I see a lot common these days, where we want to iterate over items in a list and invoke some method. The current syntax allows us to do this by the following pattern:

const newArray = array.map(item => item.someMethod())

My proposal is to create new operator & to replace the common boilerplate part and introduce the pattern such as following:

const newArray = array.map(&.someMethod())

This will reduce some cognitive complexity and thus improving developer productivity, and reduce a good amount of bundle size.

PS: This is my first post here. Please let me know if I am missing something in the process. Thanks.

Example from Ruby here: to_proc (Symbol) - APIdock

That seems like a lot to add to the language to avoid what could be 4 characters _=>_ - it seems to me like it would be more complexity to add a new way to do this?

1 Like

This partial application proposal is related. It allows you to put a "?" as one of the function parameters to create a partially applied function, that can later be used in places like array.map()

For example:

const newArray = array.map(transformElement(?))

It's certainly much more restrictive than what you're asking for. There's been a little talk (in the bug reports section, feel free to look around) about allowing partial expressions, where the "?" can be placed anywhere in the expression (see this for example). This, unfortunately, carries a lot of issues. For example, you now need some algorithm to determine where the boundaries of this partial expression should lie, or have some explicit syntax to mark the boundaries. You also need to figure out what should happen if two "?" appear in the same expression (is that one function with two parameters, or two separate functions - there's use cases for both). By the time you achieve this, you may be left with some fairly complicated syntax, and @ljharb's arrow function suggestion would have been simpler.

1 Like

to avoid what could be 4 characters _=>_

If you take account for currying this could effect in compounding manner. I definitely see merit in that.
Even though I won't say that writing extra syntax is hurting a lot, but will certainly won't like to settle for less.

Given that Javascript is generally an uncurried language by default, and most Javascript users don't do currying, I would hope/expect multiple uses of & in a single expression to result in a single, multi-parameter function, not a curried function, as that would be a more useful result for most people. This is actually the direction that the partial-application proposal is taking too - multiple uses of ? will result in a single, multi-parameter function.