-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
last.js
47 lines (39 loc) · 831 Bytes
/
last.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use strict';
var isNumber = require('is-number');
/**
* Returns the last item, or last `n` items of an array.
*
* ```js
* last(['a', 'b', 'c', 'd', 'e'], 2)
* //=> ['d', 'e']
* ```
*
* @name .last
* @param {Array} `array`
* @param {Number} `n` Number of items to return, starting with the last item.
* @return {Array}
* @api public
*/
module.exports = function last_(arr, fn) {
if (!Array.isArray(arr)) {
throw new TypeError('utils#array.last() expects an array.');
}
var len = arr.length;
if (len === 0) {
return [];
}
if (!fn) return arr[arr.length - 1];
if (isNumber(fn)) {
return arr.slice(-fn);
}
if (typeof fn === 'function') {
var val, i = 0;
while (len--) {
val = arr[i++];
if (fn(val, i, arr)) {
return val;
}
}
}
return [];
};