1 | module.exports = function(arr, start, end, step) {
|
2 |
|
3 | if (typeof start == 'string') throw new Error("start cannot be a string");
|
4 | if (typeof end == 'string') throw new Error("end cannot be a string");
|
5 | if (typeof step == 'string') throw new Error("step cannot be a string");
|
6 |
|
7 | var len = arr.length;
|
8 |
|
9 | if (step === 0) throw new Error("step cannot be zero");
|
10 | step = step ? integer(step) : 1;
|
11 |
|
12 |
|
13 | start = start < 0 ? len + start : start;
|
14 | end = end < 0 ? len + end : end;
|
15 |
|
16 |
|
17 | start = integer(start === 0 ? 0 : !start ? (step > 0 ? 0 : len - 1) : start);
|
18 | end = integer(end === 0 ? 0 : !end ? (step > 0 ? len : -1) : end);
|
19 |
|
20 |
|
21 | start = step > 0 ? Math.max(0, start) : Math.min(len, start);
|
22 | end = step > 0 ? Math.min(end, len) : Math.max(-1, end);
|
23 |
|
24 |
|
25 | if (step > 0 && end <= start) return [];
|
26 | if (step < 0 && start <= end) return [];
|
27 |
|
28 | var result = [];
|
29 |
|
30 | for (var i = start; i != end; i += step) {
|
31 | if ((step < 0 && i <= end) || (step > 0 && i >= end)) break;
|
32 | result.push(arr[i]);
|
33 | }
|
34 |
|
35 | return result;
|
36 | }
|
37 |
|
38 | function integer(val) {
|
39 | return String(val).match(/^[0-9]+$/) ? parseInt(val) :
|
40 | Number.isFinite(val) ? parseInt(val, 10) : 0;
|
41 | }
|