diff --git a/mod.ts b/mod.ts index 58c0a48..a199bb2 100644 --- a/mod.ts +++ b/mod.ts @@ -5,6 +5,7 @@ * Released under the MIT License. */ +/**/ export function lastItem(array: readonly T[]): T; export function lastItem(array: readonly T[], length: number): T[]; export function lastItem(array: readonly T[], length = 1) { @@ -12,25 +13,29 @@ export function lastItem(array: readonly T[], length = 1) { throw new TypeError("Expected an array."); } - if (array.length <= 0) { + let index = array.length; + + if (index <= 0) { throw new RangeError("Expected an array with at least one item."); } if (length === 1) { - return array[array.length - 1]; + return array[index - 1]; } if (!Number.isInteger(length)) { throw new TypeError("Expected an integer."); } - if (length > array.length) { + if (length > index) { throw new RangeError("More items were requested than there are."); } - const result = Array.from({ length }); + if (length === index) { + return array; + } - let index = array.length; + const result = []; while (length--) { result[length] = array[--index]; diff --git a/readme.md b/readme.md index 549594b..3847d2f 100644 --- a/readme.md +++ b/readme.md @@ -82,20 +82,17 @@ it's strange behavior, here are some things I noticed. - [If you send an empty array it will return null](https://github.com/jonschlinkert/array-last/blob/master/index.js#L16) -> This module will throw a `RangeError` +> This module would throw a `RangeError` - [If you send a parameter that is not a number as length it will be changed to `1`](https://github.com/jonschlinkert/array-last/blob/master/index.js#L20) > This module would throw a `TypeError` -- [If you send as expected length a number greater than the length of the array, - it will give you an array with `undefined` in some index.](https://github.com/jonschlinkert/array-last/issues/6) +- [If you send a number larger than the length of the array, the array will be filled with `undefined`.](https://github.com/jonschlinkert/array-last/issues/6) ```javascript -const last = require("array-last"); - -last(["a", "b", "c", "d", "e", "f"], 7); //=> [ undefined, 'a', 'b', 'c', 'd', 'e', 'f' ] +last(["a", "b", "c"], 4); //=> [ undefined, 'a', 'b', 'c' ] ``` > This module would throw a `RangeError`