Skip to content

Instantly share code, notes, and snippets.

@br3nt
Last active August 21, 2023 02:11
Show Gist options
  • Save br3nt/8395c27a0aa3ef93a1e9fc1da3bbfa41 to your computer and use it in GitHub Desktop.
Save br3nt/8395c27a0aa3ef93a1e9fc1da3bbfa41 to your computer and use it in GitHub Desktop.
Backlava in Javascript

See: https://sampleprograms.io/projects/baklava/javascript/

My attempt at backlava in JS.

Fetaures and difference to other implementation:

  • memoise the spaces and stars
  • use of substr to 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:

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

This version contains a single loop and is based off https://sampleprograms.io/projects/baklava/phix/

function backlava(x) {
  let stars = '*'.repeat((x * 2) + 1)
  let spaces = ' '.repeat(x)
  let builder = []

  for (i = -x; i <= x; i++) {
      builder.push(`${spaces.substr(x - Math.abs(i))} ${stars.substr(0, (x * 2) + 1 - (Math.abs(i) * 2))}`)
  }

  let backlavaStr = builder.join("\n")

  return backlavaStr
}

console.log(backlava(20))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment