Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Return the item at the given index in the array, allowing for positive and negative integers. Negative integers count back from the last item in the array.
/**
* Return the item at the given index in the array, allowing for positive and
* negative integers. Negative integers count back from the last item
* in the array.
*
* {@link https://gist.github.com/kieranbarker/1bb4ae463f3cd8138b4805983de49f4d}
*
* @param {Array} array The array
* @param {Number} index The index
* @returns {*} The item at the given index
*/
function array_at(array, index) {
if (!Array.isArray(array)) {
throw new TypeError('Expected first argument to be an array.');
}
if (typeof index !== 'number') {
throw new TypeError('Expected second argument to be a number.');
}
return index >= 0 ? array[index] : array[array.length + index];
}
@kieranbarker
Copy link
Author

kieranbarker commented May 17, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment