Say I have the following checkbox:
<input type="checkbox" value="1-25" />
To get the two numbers that define the boundaries of range I'm looking for, I use the following jQuery:
var value = $(this).val();
var lowEnd = Number(value.split('-')[0]);
var highEnd = Number(value.split('-')[1]);
How do I then create an array that contains all integers between lowEnd
and highEnd
, including lowEnd
and highEnd
themselves? For this specific example, obviously, the resulting array would be:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
You can design a range method that increments a 'from' number by a desired amount until it reaches a 'to' number. This example will 'count' up or down, depending on whether from is larger or smaller than to.
If you ever want to step by a decimal amount : Array.range(0,1,.01) you will need to truncate the values of any floating point imprecision. Otherwise you will return numbers like 0.060000000000000005 instead of .06.
This adds a little overhead to the other version, but works correctly for integer or decimal steps.
Adding http://minifiedjs.com/ to the list of answers :)
Code is similar to underscore and others:
Docs here: http://minifiedjs.com/api/range.html
I use minified.js because it solves all my problems with low footprint and easy to understand syntax. For me, it is a replacement for jQuery, MustacheJS and Underscore/SugarJS in one framework.
Of course, it is not that popular as underscore. This might be a concern for some.
Minified was made available by Tim Jansen using the CC-0 (public domain) license.
Solving in underscore
this is roughly equivalent to
breaking it down:
this creates a sparse matrix of the correct nominal length. Now the problem with a sparse matrix is that although it has the correct nominal length, it has no actual elements, so, for
gives us
Then
passes the sparse matrix as an argument list to the Array constructor, which produces a dense matrix of (actual) length targetLength, where all elements have undefined value. The first argument is the 'this' value for the the array constructor function execution context, and plays no role here, and so is null.
So now,
yields
finally
makes use of the fact that the Array.map function passes: 1. the value of the current element and 2. the index of the current element, to the map delegate/callback. The first argument is discarded, while the second can then be used to set the correct sequence value, after adjusting for the start offset.
So then
yields
I highly recommend underscore or lo-dash libraries:
http://underscorejs.org/#range
(Almost completely compatible, apparently lodash runs quicker but underscore has better doco IMHO)
Both libraries have bunch of very useful utilities.