-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
46 lines (36 loc) · 1 KB
/
index.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
/**
* @description An inline way to make an array of integers.
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @returns {number[]} Array from start to end, inclusive.
*/
const range = function range(start, end) {
if (typeof start !== 'number') {
throw new Error('start must be a number');
}
if (typeof end !== 'number') {
throw new Error('end must be a number');
}
if (start === end) {
return [start];
}
const incrementOrDecrement = start < end ?
(x) => x + 1 :
(x) => x - 1;
const isOutOfRange = start < end ?
(x) => x > end :
(x) => x < end;
const makeArray = function makeArray(value, aggregator = []) {
const current = incrementOrDecrement(value);
if (isOutOfRange(current)) {
return aggregator;
}
if (value === start) {
aggregator.push(start);
}
aggregator.push(current);
return makeArray(current, aggregator);
};
return makeArray(start);
};
module.exports = { range };