Skip to content

Commit 00d7b2c

Browse files
committed
fix: correctly return nth last entry when passing second argument
1 parent fa0e1a9 commit 00d7b2c

File tree

3 files changed

+4
-3
lines changed

3 files changed

+4
-3
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ $ yarn add array-last
1111
## Usage
1212

1313
```javascript
14-
const last = require('array-last');
14+
const last = require('array-nth-last');
1515

1616
const arr = [1, 2, 3, 4, 5];
1717

index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ function nthLast(array, n = 0) {
22
if (!Array.isArray(array)) {
33
throw new Error('First argument must be an array');
44
}
5-
return array[array.length - (1 + n)];
5+
6+
return n === 0 ? array[array.length - (1 + n)] : array[array.length - n];
67
}
78

89
module.exports = nthLast;

test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ test('last', t => {
1010
test('3rd last', t => {
1111
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1212
const lastEntry = nthLast(arr, 2);
13-
t.is(lastEntry, 7);
13+
t.is(lastEntry, 8);
1414
});
1515

1616
test('Invalid argument', t => {

0 commit comments

Comments
 (0)