/**
* Create a range string which can be evaluated to a native array.
*
* @param {int} start
* @param {int} end
* @return {string}
* @api public
*/
function range(start, end) {
s = parseInt(start), e = parseInt(end), b = '[' + s
if (e > s) while (++s <= e) b += ',' + s
else while (--s >= e) b += ',' + s
return b + ']'
}
Refactorings
No refactoring yet !
Paul Wilkins
March 17, 2009, March 17, 2009 22:53, permalink
Some tidy ups can occur here. The variables aren't meaningful, there are nearly duplicate while loops, and the square brackets are being added on in separate locations.
Here's how I might tidy this up:
function range(start, end) {
start = parseInt(start);
end = parseInt(end);
var range = [],
direction = (end > start) ? 1 : -1,
i;
for (i = start; i <= end; i += direction) {
range.push(i);
}
return '[' + range.join(',') + ']';
}
Tj Holowaychuk
March 18, 2009, March 18, 2009 00:23, permalink
s / e / b == start / end / buffer :P common now! haha, here we go. I find that for the micro private APIs small variable names are easier to read, however public of course should be meaningful like you mentioned. pretty happy with this
function range(start, end) {
current = parseInt(start), end = parseInt(end), numbers = []
if (end > current) while (++current <= end) numbers.push(current)
else while (--current >= end) numbers.push(current)
return '[' + numbers.join() + ']'
}
Tj Holowaychuk
March 18, 2009, March 18, 2009 00:26, permalink
drrr, dont even need join what am i tihnking
function range(start, end) {
current = parseInt(start), end = parseInt(end), numbers = []
if (end > current) while (++current <= end) numbers.push(current)
else while (--current >= end) numbers.push(current)
return '[' + numbers + ']'
}
Tj Holowaychuk
March 18, 2009, March 18, 2009 00:31, permalink
AND forgot to initialize with the starting value since im not using that buffering technique anymore
function range(start, end) {
current = parseInt(start), end = parseInt(end), values = [current]
if (end > current) while (++current <= end) values.push(current)
else while (--current >= end) values.push(current)
return '[' + values + ']'
}
paul.wilkins.myopenid.com
March 18, 2009, March 18, 2009 00:35, permalink
And don't forget to initialize the values variable, otherwise it'll become global
Tj Holowaychuk
March 18, 2009, March 18, 2009 00:42, permalink
meh lol I honestly never have any issues with declarations, there are maybe two within all 1000+ lines of JSpec and its fine, not like you ever just push() to a random values var without defining it first, but I suppose it could cause some false positives or issues if the developer is flakey
I use this in a JS interpreted grammar for JSpec, if anyone has a better solution let me know :D