/
27.06.2021 at 12:49 pm
Cuttings

Eloquent Javascript / Chapter 2, Exercise 03

Chessboard - in which I review ternary operators.

Problem

Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines.

At each position of the grid there is either a space or a "#" character. The characters should form a chessboard.

Passing this string to console.log should show something like this:

   # # # #   
    # # # #  
   # # # #   
    # # # #  
   # # # #   
    # # # #  
   # # # #

Discussion

  1. Personally I'm not a fan of the "?" syntax. I think Python's ternary operator looks cleaner.

  2. It's possible to use a ternary operator in place of a regular if is possible, but I find it quite unreadable.

Solution

  1. Solution 1: Explicit and repetitive.

    ``` javascript
    grid_size = 8
    invert = true
    
    for (let row = 0; row < grid_size; row++) {
        row_string = `${row+1} `
    
        if (invert) {
            white = " "
            black = "#"
        } else {
            white = "#"
            black = " "
        }
    
        for (let col = 0; col < grid_size; col++) {
    
            if (col % 2 === 0) {
                row_string += `${white}`
            } else {
                row_string += `${black}`
            }
        }
        console.log(row_string)
        invert = invert ? false : true
    }
    ```
    
  2. Solution 2: cleaner, shorter. The ternary operator here isn't as readable as an if statement. I also find it quite confusing, since the .reverse() method comes as a statement, and does not mark a return value.

    ```javascript
    grid_size = 8
    invert = true
    switches = [" ", "#"]
    
    for (let row = 0; row < grid_size; row++) {
        row_string = `${row + 1} `
        row % 2 === 0 ? switches : switches.reverse()
    
        for (let col = 0; col < grid_size; col++) {
    
            if (col % 2 === 0) {
                row_string += `${switches[0]}`
            } else {
                row_string += `${switches[1]}`
            }
        }
        console.log(row_string)
    }
    ```
    

Filed under:
#
Words: 342 words approx.
Time to read: 1.37 mins (at 250 wpm)
Keywords:
, , , , , , , , ,

Other suggested posts

  1. 02.04.2023 at 01:03 pm / Witching May Die, But Not Litigation
  2. 20.08.2020 at 08:59 pm / A Case for Legalese (Or Not)
  3. 14.12.2018 at 03:09 pm / Recursion, Succinctly Put
  4. 15.12.2017 at 12:00 am / The Breakings of Julia
  5. 24.01.2016 at 12:00 am / Prayers Like Magic
  6. 07.07.2014 at 12:00 am / If I Cannot Strengthen Our Bench
  7. 21.04.2012 at 12:00 am / Cinematic Mass Effect
  8. 25.09.2010 at 12:00 am / 汗牛充棟
  9. 24.08.2010 at 12:00 am / Correspondences With Matt Treyvaud
  10. 14.08.2010 at 12:00 am / Basic Kanji Learning Principles
© Wan Zafran. See disclaimer.