Skip to content
This repository was archived by the owner on Mar 10, 2024. It is now read-only.
This repository was archived by the owner on Mar 10, 2024. It is now read-only.

Using iterable rest syntax #31

@jridgewell

Description

@jridgewell

I recently had the need to get the last-ish elements again. Twice actually:

  1. Getting matchIndex from String.p.replace when using a function:

    string.replace(pattern, (fullMatch, ...submatches, matchIndex, fullString) => {
      // `matchIndex` is always the second to last param (the full string is the last param).
      // There may be many submatch params, depending on the pattern.
    });
  2. Getting the last element of an array of IntersectionObserverEntry:

    const io = new IntersectionObserver(entries => {
      // There may be many entries, but only the last one
      // is needed to see if element is currently visible.
      // The rest are stale.
      const [..., last] = entries;
    })

I propose repurposing iterable's rest ... syntax (with an optional binding) to get the last (or last-ish) elements:

// Grab the last, don't care about anything else.
const [..., last] = iterable;

// Grab second-to-last, throw the rest away.
const [..., secondToLast, last] = iterable;

// Can even keep the initial elements
const [...initial, last] = iterable;

// Can repurpose inside params:
function foo(..., last) {
}

It's not perfect (there's no equivalent way to set the last item), but it seems natural with destructuring syntax. We just need to prevent multiple ... from being used it the same iterable destructure.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions