function diamond(n) {
if (n % 2 == 0 || n < 1) return null
var x = 0,
add, diam = line(x, n);
while ((x += 2) < n) {
add = line(x / 2, n - x);
diam = add + diam + add;
}
return diam;
}
function repeat(str, x) {
return Array(x + 1).join(str);
}
function line(spaces, stars) {
return repeat(" ", spaces) + repeat("*", stars) + "\n";
}
console.log(diamond(5));
The code prints the diamond shape using asterisks.
I was trying to understand this code (other person's code).
I thought the result would look like
*
***
*****
*****
*****
***
*
But it worked perfectly well, and I realized the part while ((x +=2) < n)
did make difference.
So my question is: what is the difference between while ((x += 2) < n) { ... } and while (x < n) { ... x += 2 }?