I am new to javascript still trying to learn things.
I've found a solution to a problem about a function that should generate all combinations of a characters within a string.
I'm trying to figure out:
- What is happening inside the loop?
- How does the loops execute step by step?
I cannot figure how it reaches to that final output.
I tried for a long time to figure out but I m not sure what happens inside those loops. I don't understand tho how it gets "ab", "ac". ... together in the final output and where arrTemp pushes result[x] and char. I saw that the result array is initially empty, then is concatenated with arrTemp.
Here is the code I'm struggling with:
function combString(str){
var lenStr = str.length;
var result = [];
var indexCurrent = 0;
while(indexCurrent < lenStr){
var char = str.charAt(indexCurrent);
var x;
var arrTemp = [char];
for(x in result) {
arrTemp.push(""+result[x]+char);
}
result = result.concat(arrTemp);
indexCurrent++;
}
return result;
}
console.log(combString("abc"));
And this is the output
["a", "b", "ab", "c", "ac", "bc", "abc"]