diff --git a/index.js b/index.js index 8c32f3b..4a86cb4 100644 --- a/index.js +++ b/index.js @@ -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'); @@ -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; } } diff --git a/test.js b/test.js index 7f840d9..0d26932 100644 --- a/test.js +++ b/test.js @@ -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 => {