xiqe / code-train

前端算法

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Christmas tree

xiqe opened this issue · comments

Christmas tree

Create a function that returns a christmas tree of the correct height.

For example:

hieght = 5 should return:

    *    
   ***   
  *****  
 ******* 
*********

Height passed is always an integer between 0 and 100.

Use \n for newlines between each line.

Pad with spaces so each line is the same length. The last line having only stars, no spaces.

reply

function christmasTree(height) {
  let result = '';
  for(let i=height;i>0;i--){
    let cur = [];
    for(let j=0;j<2*height+1;j++){
      cur[j] = (j<=2*height-i && j>=i)?'*':' '
    }
    result += cur.join('') + '\n'
  }
  return result
}