HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Chess board in JS

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
chessboardstackoverflow

Problem

I've completed the small challenge in the eloquent JS book to create a chess board pattern:


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 chess board. When you have a program that generates this
pattern, define a variable size = 8 and change the program so that it
works for any size, outputting a grid of the given width and height.

I've used a function instead of a variable, but what do you think about my little script?



`function chessboard(size) {
var output = "";
for(var i = 0; i

Solution

You always append two squares at a time, so the output will be wrong if size is odd.

String concatenation is a rather expensive operation. Since strings in JavaScript are immutable, each += involves allocating a new string, copying the entire contents of the string, then copying the characters to be appended. Therefore, it would be a good idea to reduce the number of concatenation operations. (The obvious change would be to coalesce two append operations into output += " #"; and output += "# ", but as I noted above, that produces wrong results.)

One improvement would be to construct an even line (e.g. " # # # #\n") and an odd line (e.g. "# # # # \n"), then compose the board a line at a time.

An eloquent solution would probably involve Array.join("\n"), but I suppose that would not be an expected solution at this early point in the book.

Context

StackExchange Code Review Q#123180, answer score: 3

Revisions (0)

No revisions yet.