Runtime Complexity: O(n^2)
/*Create a staircase based on user input n.
steps(5) should return the below output:
"# "
"## "
"### "
"#### "
"#####"
*/
const steps = (n) => {
if( n > 0){
for (let row = 0; row < n; row++) {
let step = '';
for (let col = 0; col < n; col++) {
col <= row ? step += '#' : step += ' ';
}
console.log(step);
}
return
}
console.log(`please give a number greater than 0`)
}
steps(5);
/* Output
"# "
"## "
"### "
"#### "
"#####" */
String.prototype.repeat()
Introduced in ES2015+, the repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
Syntax: str.repeat(count)
count is an integer between 0 and infinity(positive) indicating the number of times to repeat the string.
Code | Output |
‘abc’.repeat(-1) | RangeError |
‘abc’.repeat(0) | ” |
‘abc’.repeat(1) | ‘abc’ |
‘abc’.repeat(2) | ‘abcabc’ |
‘abc’.repeat(3.5) | ‘abcabcabc’ // Uses floor |
‘abc’.repeat(1/0) | Range Error |
Note: If the total length of the string to be returned equals or exceeds (1 << 28, i.e., 2^28) then, this method throws a RangeError as most modern browsers can’t handle strings longer than that.
if((str.length * count) >= 1 << 28) // This
/* A simplified solution using String.prototype.repeat
*/
const steps = (n) => {
for(let i = 1; i <= n; i++) {
let step = '#'.repeat(i) + ' '.repeat(n-i);
console.log(step);
}
}
steps(5);
/* Output
"# "
"## "
"### "
"#### "
"#####" */