@newdash/newdash
Version:
javascript/typescript utility library
50 lines (49 loc) • 1.23 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.nth = void 0;
const isIndex_1 = __importDefault(require("./.internal/isIndex"));
const toInteger_1 = __importDefault(require("./toInteger"));
/**
* @ignore
* @private
* @internal
* @param array
* @param n
*/
function baseNth(array, n) {
const length = array.length;
if (!length) {
return;
}
n += n < 0 ? length : 0;
return (0, isIndex_1.default)(n, length) ? array[n] : undefined;
}
/**
* Gets the element at index `n` of `array`. If `n` is negative, the nth
* element from the end is returned.
*
* @since 5.7.0
* @category Array
* @param array The array to query.
* @param n The index of the element to return.
* @returns Returns the nth element of `array`.
* @example
*
* ```js
* const array = ['a', 'b', 'c', 'd']
*
* nth(array, 1)
* // => 'b'
*
* nth(array, -2)
* // => 'c'
* ```
*/
function nth(array, n = 0) {
return (array && array.length) ? baseNth(array, (0, toInteger_1.default)(n)) : undefined;
}
exports.nth = nth;
exports.default = nth;