Proposal: rest operator in middle of array

Ethan Resnick ethan.resnick at gmail.com
Thu Jun 6 16:53:24 UTC 2019


Long-time mostly-lurker on here. I deeply appreciate all the hard work that
folks here put into JS.

I've run into a couple cases now where it'd be convenient to use a rest
operator at the beginning or middle of an array destructuring, as in:

```
const [...xs, y] = someArray;
```

Or, similarly, in function signatures:

```
function(...xs, y) { }
```

The semantics would be simple: exhaust the iterable to create the array of
`xs`, like a standard rest operator would do, but then slice off the last
item and put it in `y`.

For example, I was working with some variable argument functions that, in
FP style, always take their data last. So I had a function like this:

```
function match(...matchersAndData) {
  const matchers = matchersAndData.slice(0, -1);
  const data = matchersAndData[matchersAndData.length - 1];
  // do matching against data
}
```

Under this proposal, the above could be rewritten:

```
function reduce(...matchers, data) { /* ... */ }
```

Another example: a function `pad`, which takes a target length and a string
to pad, with an optional padding character argument in between:

```
function pad(targetLength, ...paddingCharAndOrData) {
  const [paddingChar = " "] = paddingCharAndOrData.slice(0, -1);
  const data = paddingCharAndOrData[paddingCharAndOrData.length - 1];

  // pad data with paddingChar to targetLength;
}
```

With this proposal, that could be rewritten:

```
function pad(targetLength, ...opts, data) {
  const [paddingChar = " "] = opts;
  // pad data with paddingChar to targetLength;
}
```

I'm curious if this has been considered before, and what people think of
the idea.

Obviously, if `...a` appeared at the beginning or middle of a list, there
would have to be a fixed number of items following it, so a subsequent rest
operator in the same list would not be allowed.

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20190606/94957d91/attachment.html>


More information about the es-discuss mailing list