I need to call the following function cross
4 times, for all permutations of the x
and y
variable with the values 1 and -1;
my approach:
var p = [-1, 1];
p.forEach(function(x) {
p.forEach(function(y) {
cross(x, y);
});
});
Is there a shorter way of doing this?
If you want to be extra functional, you can use map
and then reduce
the arrays into one. I don't think it would necessarily be any more efficient than what you have now, nor is it much simpler (it is more functional, just slightly).
var d = [-1, 1];
var r = d.reduce(function(p, x) {
return p.concat(d.map(function(y) {
return cross(x, y);
}));
}, []);
document.getElementById('r').textContent = JSON.stringify(r);
<pre id=r></pre>
I really don't think there is an algorithm with better than n^2 efficiency to produce n^2 combinations.
There is some overhead in calling a function. e.g. putting the return pointer on the stack. It would probably be slightly faster to use two for loops rather than callbacks to forEach.
var p = [-1, 1];
for (var x = 0; x < p.length; x++) {
for (var y = 0; y < p.length; y++) {
cross(p[x], p[y]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With