Get an item at a negative or wrapping index of array-likes
Carousels, playlists, and color palettes all need “the item at position n“, where n can be negative (count from the end) or can run past the end and wrap back to the start. Write one helper that handles both.
Implement itemAt(collection, index, options). It returns the element of collection at index, or undefined if there is none.
itemAt(collection, index, options?) // => element | undefined
// options: { wrap?: boolean }
collection is an array, a string, or an array-like object: an object with a non-negative integer length and elements under the keys 0, 1, …. For a string, return the character at that position as a one-character string (one UTF-16 code unit, like str[i]).
index with Number(index). If the result is NaN, use 0.2.9 becomes 2 and -1.5 becomes -1.Infinity or -Infinity, return undefined, even with wrap.-1 is the last element.0 to length - 1 returns undefined.{ wrap: true }4 is 0, 9 is 1, and -5 is 3.undefined.const slides = ['intro', 'pricing', 'faq', 'signup'];
itemAt(slides, 1); // => 'pricing'
itemAt(slides, -1); // => 'signup'
itemAt(slides, 4); // => undefined
itemAt(slides, -5); // => undefined
itemAt(slides, 4, { wrap: true }); // => 'intro'
itemAt(slides, -5, { wrap: true }); // => 'signup'
itemAt(slides, '2'); // => 'faq'
itemAt(slides, 1.9); // => 'pricing'
itemAt(slides, 'next'); // => 'intro' (NaN becomes 0)
itemAt('#ff8800', -2); // => '0'
itemAt({ length: 2, 0: 'a', 1: 'b' }, -1); // => 'b'
itemAt([], 0, { wrap: true }); // => undefined
Array.prototype.at or String.prototype.at.undefined.