Exercise: range function - kdaisho/Blog GitHub Wiki
range function
Write a range function that takes three arguments, start, end and skip, and returns an array containing all the numbers from start up to (and including) end, skipping the number at index indicated by skip argument.
Example:
range(2, 10);
// [2, 3, 4, 5, 6, 7, 8, 9, 10]
range(2, 10, 1);
// [2, 4, 5, 6, 7, 8, 9, 10]
// number 3 was skipped because its index is 1
Solution
function range(first, last, skip) {
var result = [];
var i;
if (first < last) {
for (i = 0; first <= last; i++, first++) {
if (i === skip) continue;
result.push(first);
}
}
else {
for (i = 0; first >= last; i++, first--) {
if ( i === skip) continue;
result.push(first);
}
}
return result;
}
It gets the job done.
But as you can see, code base is somewhat repeating within if statement. I've tried to organize with no success. Leaving as an assignment for myself.