0

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++;
}
2
  • There isn't much you could do to optimize this, but you could remove either line or i, as both increase by a set amount each iteration. (Note that i = line * 2 - 1.) After that, there are some micro-optimizations, but usually the browser takes care of those. Commented Jun 18, 2020 at 13:43
  • There's a whole website for these kinds of questions - codegolf.stackexchange.com You might consider migrating it there for even more answers. Commented Jun 18, 2020 at 18:26

4 Answers 4

3

that ?

let s = '*'
for(let p=15;p--;) 
  {
  console.log( ' '.repeat(p) + s)
  s += '**'
  }
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

0

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; }

Comments

0

console.log(Array.from({length:15},(_,i)=>"*".repeat(i*2+1).padStart(15+i)).join`\n`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.