You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Mar 10, 2024. It is now read-only.
I recently had the need to get the last-ish elements again. Twice actually:
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.});
Getting the last element of an array of IntersectionObserverEntry:
constio=newIntersectionObserver(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 elementsconst[...initial,last]=iterable;// Can repurpose inside params:functionfoo(...,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.