jashkenas/coffee-script — Issue #1989: Improvements to array destructuring
Author: devongovett
Created: 2011-12-30 05:54:27+00:00
State: open

While writing [ALAC.js](http://github.com/ofmlabs/alac.js), I found a few instances where some additions and improvements to the way the destructuring assignment works with arrays would be helpful.

Currently, `Array#slice` is used to perform many types of destructuring assignments. I think there are some compelling reasons why this should be avoided in favor of inlining.

### a) Using slice is slower than inlining and doesn't work with typed arrays

Currently this:

```coffeescript
[a0, a1, a2, a3] = array[2...6]
```

compiles to:

```javascript
_ref = array.slice(2, 6), a0 = _ref[0], a1 = _ref[1], a2 = _ref[2], a3 = _ref[3];
```

which uses a (slow) `slice` call to pull the values out. Would it be possible to instead compile this to:

```javascript
a0 = array[2], a1 = array[3], a2 = array[4], a3 = array[5];
```

### b) It doesn't work in reverse order

Additionally, I should be able to pull values out of an array in reverse order, for example:

```coffeescript
[a0, a1, a2, a3] = array[3..0]
```

Currently, this compiles to:

```javascript
_ref = array.slice(3, 1), a0 = _ref[0], a1 = _ref[1], a2 = _ref[2], a3 = _ref[3];
```

Which doesn't work, of course. It should compile to:

```javascript
a0 = array[3], a1 = array[2], a2 = array[1], a3 = array[0];
```

[Here](https://github.com/ofmlabs/alac.js/blob/master/Aurora/core/stream.coffee#L206) is an example of where I would have used a destructuring assignment in ALAC.js, but couldn't.

### c) Inlining is much cleaner, especially when putting values into an array

Finally, when using a destructuring assignment to put values into an array, a number of array-methods are used. For example, this CoffeeScript:

```coffeescript
array[0...4] = [a0, a1, a2, a3]
```

compiles to:

```javascript
[].splice.apply(array, [0, 4].concat(_ref2 = [a0, a1, a2, a3])), _ref2;
```

which works (even with typed arrays), but isn't "what I would have written". It's a bit too clever for my taste! I think it should be compiled to this:

```javascript
array[0] = a0, array[1] = a1, array[2] = a2, array[3] = a3;
```

which is both faster, shorter and more readable! See [here](https://github.com/ofmlabs/alac.js/blob/master/src/dp_dec.coffee#L219) for a real world example of doing this manually in ALAC.js.

### In summary...

Using `slice` works, but there are some drawbacks:

1. It is slower than inlining.
2. It doesn't work with typed arrays, which don't have a `slice` method but are array-like. This is true of many common JavaScript libraries as well.
3. It doesn't work in reverse.

Let me know what you think!