Skip to content

Instantly share code, notes, and snippets.

@kieranbarker
Created May 16, 2021 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kieranbarker/1bb4ae463f3cd8138b4805983de49f4d to your computer and use it in GitHub Desktop.
Save kieranbarker/1bb4ae463f3cd8138b4805983de49f4d to your computer and use it in GitHub Desktop.
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

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