Reputation: 3606
I have Python function returning me ip addresses of i.e. 10.1-2.128-256.1 (2nd byte changing from 1-2 and 3rd byte changing from 128 to 256)
def list1s():
return ["10." + str(x) + "." + str(y) + ".1" for x in range(1, 3) for y in range(128, 256)]
I am trying to do the same in Nodejs v4.2.4. So far I found how to do range in NodeJS. I think next step would be to use map ?
function list1s(){
return Array.from(Array(256).keys()).slice(128,256)
}
Upvotes: 0
Views: 49
Reputation: 6279
First, you need to wrap your range into a function:
functions range(begin, end) {
return Array.from(Array(end).keys()).slice(begin, end);
}
After then, to get all possible combinations of x
and y
, you need to get a cartesian product of two arrays:
function cartesian() {
var r = [], args = Array.from(arguments);
args.reduceRight(function(cont, factor, i) {
return function(arr) {
for (var j=0, l=factor.length; j<l; j++) {
var a = arr.slice(); // clone arr
a[i] = factor[j];
cont(a);
}
};
}, Array.prototype.push.bind(r))(new Array(args.length));
return r;
}
This function from two arrays [1,2]
and [1,2]
will produce an array [[1,1], [1,2], [2,1], [2,2]]
.
With these two helper functions making a list you need is easy:
function list() {
return cartesian(range(1,3), range(128, 256)).map(function(args) {
return '10.' + args[0] + '.' + args[1] + '.1';
});
}
Upvotes: 1