The problem lies in the fact that, unlike other languages, to repeat a character in Javascript, you cannot do something like this:
'#' * 5; // NaN
Must use the method String.prototype.repeat
.
Anyway, you can do something like this:
function escada(degraus) {
const escadaArray = [];
const espacoChar = ' ';
const degrauChar = '#';
for (let i = 1; i <= degraus; i++) {
const espacosParaAdd = espacoChar.repeat(degraus - i);
const degrausParaAdd = degrauChar.repeat(i);
escadaArray.push(espacosParaAdd + degrausParaAdd);
}
return escadaArray;
}
console.log(escada(3));
console.log(escada(5));
Some notes regarding the above example:
- We define the number of steps of each walk from the variable (
i
), that is incremented with each iteration;
- To calculate the number of spaces to be placed before the step, simply subtract the total number of steps from the number of steps of the current iteration (
i
).
Going a little further, if you want a slightly less imperative solution, you can do so too (example a little more advanced):
function makeStair(steps, step = '#', space = ' ') {
return Array.from(
{ length: steps },
(el, i) => space.repeat(steps - i) + step.repeat(++i)
);
}
console.log(makeStair(3));
console.log(makeStair(5));
Recommended reading: