Skip to content

Commit dc99c6f

Browse files
authored
Merge pull request #55 from jmbutler27/jobutler/range
feat: add range function (#42)
2 parents bd26fc7 + a2ae666 commit dc99c6f

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,4 @@ export * from './utils/get';
3535
export * from './utils/escape-html';
3636
export * from './utils/make-template';
3737
export * from './utils/uniq';
38+
export * from './utils/range';

src/utils/range.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Creates an array of numbers (positive and/or negative) progressing from
3+
* start up to, but not including, end. A step of -1 is used if a negative start
4+
* is specified without an end or step. If end is not specified, it's set to
5+
* start with start then set to 0.
6+
*/
7+
export function range(start: number, end?: number, step?: number): number[] {
8+
if (end === undefined) {
9+
end = start;
10+
start = 0;
11+
}
12+
13+
if (!step) {
14+
step = start < end ? 1 : -1;
15+
}
16+
17+
const length = Math.max(Math.ceil((end - start) / step), 0),
18+
result = Array(length);
19+
20+
for (let i = 0; i < length; i++) {
21+
result[i] = start + (i * step);
22+
}
23+
return result;
24+
}

tests/utils/range.test.ts

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { expect } from 'chai';
2+
import { range } from '../../src';
3+
4+
describe('range', () => {
5+
it('works when only start is provided', () => {
6+
expect(range(4)).to.eql([ 0, 1, 2, 3 ]);
7+
});
8+
9+
it('works when only start and end are provided', () => {
10+
expect(range(1, 5)).to.eql([ 1, 2, 3, 4 ]);
11+
});
12+
13+
it('works when start, end, and step is provided', () => {
14+
expect(range(0, 20, 5)).to.eql([ 0, 5, 10, 15 ]);
15+
});
16+
17+
it('works when start is set to a negative number', () => {
18+
expect(range(-4)).to.eql([ 0, -1, -2, -3 ]);
19+
});
20+
21+
it('works when step is set to zero', () => {
22+
expect(range(1, 4, 0)).to.eql([ 1, 2, 3 ]);
23+
});
24+
25+
it('works when step is a negative number ', () => {
26+
expect(range(2, -4, -2)).to.eql([ 2, 0, -2 ]);
27+
});
28+
29+
it('return an empty array when end and start are the same', () => {
30+
expect(range(0, 0)).to.eql([]);
31+
});
32+
33+
it('returns an empty array if only start is provided and equals zero', () => {
34+
expect(range(0)).to.eql([]);
35+
});
36+
37+
it('returns an empty array if arguments do not work', () => {
38+
expect(range(5, 1, 2)).to.eql([]);
39+
});
40+
41+
});

0 commit comments

Comments
 (0)