From 639cd364d0666612ccc112f55b646fbc457bd74a Mon Sep 17 00:00:00 2001 From: colinf Date: Fri, 9 Nov 2012 16:14:02 +0000 Subject: [PATCH 1/2] Add step argument --- Readme.md | 18 +++++++++++++++--- example.js | 4 +++- index.js | 14 +++++++++++--- 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/Readme.md b/Readme.md index fc4095e..1d72bbc 100644 --- a/Readme.md +++ b/Readme.md @@ -7,16 +7,21 @@ $ component install component/range -## API +## API ## - Exclusive range: +### range(start, end, step, inclusive) ### +Returns an array of integers from `start` to `end` by `step`. The default is for step to be 1. The range will be exclusive of the `end` value unless `inclusive` is truthy. + +## Examples ## + +Exclusive range: ```js range(5, 10); // => [5,6,7,8,9] ``` - Inclusive range (truthy value): +Inclusive range (truthy value): ```js range(5, 10, true); @@ -24,6 +29,13 @@ range(5, 10, 'inclusive'); // => [5,6,7,8,9,10] ``` +Inclusive range using step: + +```js +range(50, 10, -10, true); +// => [50,40,30,20,10] +``` + ## License MIT diff --git a/example.js b/example.js index a98bed6..c6919de 100644 --- a/example.js +++ b/example.js @@ -6,4 +6,6 @@ var range = require('./'); console.log(range(5, 10)); -console.log(range(5, 10, true)); \ No newline at end of file +console.log(range(5, 10, true)); +console.log(range(10, 5, -1)); +console.log(range(50, 10, -10, true)); \ No newline at end of file diff --git a/index.js b/index.js index 5328119..44b81b5 100644 --- a/index.js +++ b/index.js @@ -1,9 +1,17 @@ -module.exports = function(from, to, inclusive){ +module.exports = function(from, to, step, inclusive){ var ret = []; - if (inclusive) to++; + if (!(typeof step == "number")) { + inclusive = step; + step = 1; + }; + step = step || 1; + var reverse = step < 0; + if (inclusive) { + reverse ? to-- : to++; + } - for (var n = from; n < to; ++n) { + for (var n = from; ((!reverse && n < to) || (reverse && n > to )); n=n+step) { ret.push(n); } From 10fee40d16cd87629a416000206308a0ee6d04e4 Mon Sep 17 00:00:00 2001 From: colinf Date: Wed, 14 Nov 2012 12:11:26 +0000 Subject: [PATCH 2/2] Default to step of -1 if to < from --- example.js | 2 +- index.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/example.js b/example.js index c6919de..d919794 100644 --- a/example.js +++ b/example.js @@ -7,5 +7,5 @@ var range = require('./'); console.log(range(5, 10)); console.log(range(5, 10, true)); -console.log(range(10, 5, -1)); +console.log(range(10, 5)); console.log(range(50, 10, -10, true)); \ No newline at end of file diff --git a/index.js b/index.js index 44b81b5..f2c0810 100644 --- a/index.js +++ b/index.js @@ -3,7 +3,7 @@ module.exports = function(from, to, step, inclusive){ var ret = []; if (!(typeof step == "number")) { inclusive = step; - step = 1; + to < from ? step = -1 : step = 1; }; step = step || 1; var reverse = step < 0;