Reputation: 3500
I'm developing a solution on which I need to loop through two separate continuous number ranges. Lets say for example 1 to 5 and 10 to 15.
I'm using the following code:
var X = [];
for (i = 1; i < 6; i++) {
X.push(i);
}
for (i = 10; i < 16; i++) {
X.push(i);
}
for (var x in X) {
console.log(parseInt(X[x]));
}
This code does the job, but have a lot of overhead and unnecessary operations:
Is there any simpler/more efficient way to perform this kind of operation? Something like this:
for(x = 1 to 5, then x = 10 to 15) {
// do something with x
}
Constraints:
I've searched through SO but couldn't find any solution for this.
Thanks in advance!
Upvotes: 1
Views: 7004
Reputation: 33496
In ES6 you could create some generator functions which abstract away the looping details, and use a for...of
loop. This way you will have the readable syntax you're looking for, while not creating any large arrays.
function* ranges(...rangeDescriptors) {
for (const [min, max, step = 1] of rangeDescriptors)
for (let i = min; i < max; i += step)
yield i;
}
for (const x of ranges([1, 6], [10, 16])) {
console.log(x);
}
Upvotes: 3
Reputation: 1
You can use for..of
loop, for
loop, spread element
let res = [];
for (let [from, to] of [[1, 6], [10, 16]])
for (let x = from; x < to; x++) console.log(x); res.push(x);
console.log(res);
If requirement is to only log digits at console
, or "// do something with x" without storing result of "something" in an array, we can reduce javascript
to
for (let [from, to] of [[1, 6], [10, 16]])
for (let x = from; x < to; x++) console.log(x); // do stuff with `x`
Upvotes: 5
Reputation: 17388
This isn't necessarily more efficient, but it does keep everything nice and tidy and prevents duplication of code.
Basically, write a function that accepts an array of ranges and a callback to be executed on each iteration of the loop through the specified ranges.
The range and current index are passed to the callback, should they be needed.
function loop(ranges, callback) {
ranges.forEach(function (range) {
for (var i = range[0]; i <= range[1]; i++) callback(range, i);
});
}
var ranges = [
[1, 5],
[10, 15],
];
var callback = function (range, i) {
console.log(i);
}
loop(ranges, callback);
Upvotes: 2