One of the things I understand but dont really like about the range(), which is available in utility libraries such as lodash and YourJS, is that it produces an array of numbers ranging from the starting number to the ending number but not including the ending number. Let’s say for instance that you have to take three user input arguments which will produce a range of numbers. In order to make sure the range can include the upper bound you would have to do something like the following:


first = +prompt('Enter starting number:', 1);
step = +prompt('Enter different between each number:', 1);
last = +prompt('Enter last number:', first + step * 10);
numbers = _.range(first, last + step, step);
alert('Span of numbers:\n\t' + numbers.join(', '));

Although the above code works perfectly fine to produce an array of numbers starting at first and ending at last, it isn’t the most intuitive code to look at. It would be nice to have function that right out of the box always takes a lower bound and upper bound that are both inclusive so that reading the code becomes easier for all. For example it would be nice to be able to change the above code to something like the following:


first = +prompt('Enter starting number:', 1);
step = +prompt('Enter different between each number:', 1);
last = +prompt('Enter last number:', first + step * 10);
numbers = YourJS.span(first, last, step);
alert('Span of numbers:\n\t' + numbers.join(', '));

When reading the above code, a developer should now be able to intuitively tell numbers will contain all of the numbers starting at first and maxing out at last (inclusive). For this reason I thought it would be nice to add the following function to YourJS:

Here is an example of it working in YourJS:

As you can see, the definition also provides JSDoc annotation to indicate what the function does and what parameters can be passed. Feel free to use this function in your code. As always, happy coding! šŸ˜Ž


Leave a Reply

Your email address will not be published. Required fields are marked *