Reputation: 152
I was messing around with some basic algorithms. I wanted to know if someone has a shorter version of this one in JS to display the pyramid:
const total= 30;
let line = 1;
for (let i = 1; i < total; i = i + 2) {
console.log(' '.repeat(total / 2 - line) + '*'.repeat(i))
line++;
}
Upvotes: 0
Views: 181
Reputation: 350137
console.log(Array.from({length:15},(_,i)=>"*".repeat(i*2+1).padStart(15+i)).join`\n`);
Upvotes: 0
Reputation: 386550
An even shorter approach by using a while
statement.
This answer is highly inspired by the answer of Mister Jojo.
let s = '*',
p = 15;
while (p--) {
console.log(' '.repeat(p) + s)
s += '**';
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 588
Same using map function
function pyramid(height) {
return Array(height).fill('*')
.map((current, index) =>
' '.repeat(height - index) +
current.repeat(index).split('').join(' ') +
' '.repeat(height - index))
.join('\n');
}
console.log(pyramid(30));
Upvotes: 0
Reputation: 22265
that ?
let s = '*'
for(let p=15;p--;)
{
console.log( ' '.repeat(p) + s)
s += '**'
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 3