See: https://sampleprograms.io/projects/baklava/javascript/
My attempt at backlava in JS.
Fetaures and difference to other implementation:
- memoise the
spacesandstars - use of
substrto print the number of spaces and stars - use of a string builder instead of string concatenation
- the algorithm is contained within
backlava() backlava()returns a string rather than printing directly to the console
function backlava(x) {
let stars = '*'.repeat(x * 2)
let spaces = ' '.repeat(x)
let builder = []
for (i = 1; i < x; i++) {
builder.push(`${spaces.substr(i)} ${stars.substr((-i * 2) + 1)}`)
}
for (var i = x; i > 0; i--) {
builder.push(`${spaces.substr(i)} ${stars.substr((-i * 2) + 1)}`)
}
let backlavaStr = builder.join("\n")
return backlavaStr
}
console.log(backlava(20))Output:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
***********************
*************************
***************************
*****************************
*******************************
*********************************
***********************************
*************************************
***************************************
*************************************
***********************************
*********************************
*******************************
*****************************
***************************
*************************
***********************
*********************
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*