This is based on a previous SO post. Here I don't understand how the** if(i & Math.pow(2, j)** part is used to select the array element. The code is pasted below.
var arr = [1, 2, 3];
function generatePowerSet(array) {
var result = [];
result.push([]);
for (var i = 1; i < Math.pow(2, array.length); i++, result.push(subset))
for (var j = 0, subset = []; j < array.length; j++)
if (i & Math.pow(2, j))
subset.push(array[j]);
return result;
}
console.log(generatePowerSet(arr));
I read the answers and Mathematically I get it is using & operator and checking if it is 0 or 1, but I don't understand the logic behind it. Please can someone explain it?