How can I draw a cross in javascript

The aim is to write function drawACross which returns a cross shape with 'x' characters on a square grid of size and height of our sole input n. All non-'x' characters in the grid should be filled with a space character (" ").
The arms of the cross must only intersect through one central 'x' character, and start in the corner of the grid, so for even values of n, return "Centered cross not possible!"

If n < 3, function should return "Not possible to draw cross for grids less than 3x3!"
This is my code, but in the result the cross is not centered:

function drawACross(n) {
  if (n % 2 === 0) {
    console.log("Centered cross not possible!")
  } else if (n < 3) {
    console.log("Not possible to draw cross for grids less than 3x3!")
  } else {
    for (let i = 0; i < n; i++) {
      let arr = new Array(n)
      let y = arr.fill("", 0, arr.length)
      y.splice(arr.length - (i + 1), 1, "x")
      y.splice(i, 1, "x")
      console.log(y.join(" "))


73 thoughts on “How can I draw a cross in javascript”

  1. First off I would like to say great blog! I had a quick question that I’d like to ask if you don’t mind.

    I was curious to know how you center yourself and clear your thoughts
    prior to writing. I’ve had a tough time clearing my thoughts in getting my thoughts out there.
    I truly do take pleasure in writing but it just seems like
    the first 10 to 15 minutes are lost just trying to figure out how
    to begin. Any ideas or hints? Cheers!


Leave a Comment