Skip to content

Commit

Permalink
📝 Update Readme
Browse files Browse the repository at this point in the history
  • Loading branch information
UltiRequiem committed May 22, 2022
1 parent 73d6ced commit c52d8b2
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
15 changes: 10 additions & 5 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,32 +5,37 @@
* Released under the MIT License.
*/

/**/
export function lastItem<T>(array: readonly T[]): T;
export function lastItem<T>(array: readonly T[], length: number): T[];
export function lastItem<T>(array: readonly T[], length = 1) {
if (!Array.isArray(array)) {
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];
Expand Down
9 changes: 3 additions & 6 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down

0 comments on commit c52d8b2

Please sign in to comment.