Return a string of N spaces
Make sure to return your output, and subtract from num
each iteration:
function spaces(num) {
let mySpaces = '';
while (num-- > 0)
mySpaces += ' ';
return mySpaces;
}
console.log(
JSON.stringify(spaces(1)),
'\n',
JSON.stringify(spaces(5))
);
Ultimately, this seems to be the most elegant (and performant) approach:
const spaces = (n) => Array(n + 1).join(' ');
console.log(
JSON.stringify(spaces(1)),
'\n',
JSON.stringify(spaces(5))
);
1.1M ops/s for Array.join
vs. 86k for the while
loop.
EDIT
Totally blanked on String.repeat
, thanks to Daniel for that. Pushing 2M ops/s:
const spaces = (n) => " ".repeat(n);
console.log(
JSON.stringify(spaces(1)),
'\n',
JSON.stringify(spaces(5))
);