Skip to content

Instantly share code, notes, and snippets.

@ephys
Last active August 3, 2017 09:42
Show Gist options
  • Save ephys/2c7cd3a2afdea4e3ad2bc7910f4d3281 to your computer and use it in GitHub Desktop.
Save ephys/2c7cd3a2afdea4e3ad2bc7910f4d3281 to your computer and use it in GitHub Desktop.
const [first, second, ...middle, beforeLast, last] = anIterable;

At any step, if the iterator reaches the end of its available values, stop the algorithm.

  1. set the value of middle to a new empty array.
  2. for each variable from the first to middle excluded,
    1. iterate anIterable.
    2. set the value of the variable to the result of the iteration.
  3. for each variable from middle excluded to the last one,
    1. iterate anIterable.
    2. set the value of the variable to the result of the iteration.
  4. iterate anIterable.
  5. take the value of the first variable after middle and add it to the array value of middle.
  6. for each variable from the first variable after middle to the last one excluded.
    1. set the value of the current variable to the one of the following variable.
  7. set the value of the last variable to the result of the iteration.
  8. go to step 4.

Results

[first, second, ...middle, beforeLast, last] = [1];
// 1, undefined, [], undefined, undefined

[first, second, ...middle, beforeLast, last] = [1, 2, 3];
// 1, 2, [], 3, undefined

[first, second, ...middle, beforeLast, last] = [1, 2, 3, 4];
// 1, 2, [], 3, 4

[first, second, ...middle, beforeLast, last] = [1, 2, 3, 4, 5];
// 1, 2, [3], 4, 5

[first, second, ...middle, beforeLast, last] = [1, 2, 3, 4, 5, 6];
// 1, 2, [3, 4], 5, 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment