Skip to content

Commit

Permalink
Fix using negative value in step (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
sparebytes authored Sep 5, 2021
1 parent 939b51f commit 460a0ad
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
7 changes: 6 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ const validate = (name, value) => {
}
};

const lt = (l, r) => l < r;
const gt = (l, r) => l > r;

export default function * getRange({start = 0, end, step = 1}) {
if (step === 0) {
throw new TypeError('The `step` parameter cannot be zero');
Expand All @@ -13,7 +16,9 @@ export default function * getRange({start = 0, end, step = 1}) {
validate('end', end);
validate('step', step);

for (let index = start; index < end; index += step) {
const compare = step < 0 ? gt : lt;

for (let index = start; compare(index, end); index += step) {
yield index;
}
}
11 changes: 11 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ test('main', t => {
t.deepEqual(get({start: 0, end: 3, step: 2}), [0, 2]);
t.deepEqual(get({start: 0, end: 4, step: 2}), [0, 2]);
t.deepEqual(get({start: 0, end: 6, step: 2}), [0, 2, 4]);

t.deepEqual(get({start: 0, end: -1, step: -1}), [0]);
t.deepEqual(get({start: 0, end: -2, step: -1}), [0, -1]);
t.deepEqual(get({start: -1, end: -2, step: -1}), [-1]);
t.deepEqual(get({start: -1, end: -5, step: -1}), [-1, -2, -3, -4]);
t.deepEqual(get({start: 2, end: -2, step: -1}), [2, 1, 0, -1]);

t.deepEqual(get({start: 0, end: -2, step: -2}), [0]);
t.deepEqual(get({start: 0, end: -3, step: -2}), [0, -2]);
t.deepEqual(get({start: 0, end: -4, step: -2}), [0, -2]);
t.deepEqual(get({start: 0, end: -6, step: -2}), [0, -2, -4]);
});

test('generator', t => {
Expand Down

0 comments on commit 460a0ad

Please sign in to comment.