Skip to content

Instantly share code, notes, and snippets.

@morganwilde
Created April 17, 2020 10:04
Show Gist options
  • Save morganwilde/afc53f44ce0aa7f211156e5df9ee559a to your computer and use it in GitHub Desktop.
Save morganwilde/afc53f44ce0aa7f211156e5df9ee559a to your computer and use it in GitHub Desktop.
class Grid {
constructor(length) {
this.length = length;
this.grid = [];
for (let v = 0; v < length; v += 1) {
for (let h = 0; h < length; h += 1) {
this.grid.push(' ');
}
}
}
render() {
let buffer = '';
for (let v = 0; v < this.length; v += 1) {
for (let h = 0; h < this.length; h += 1) {
buffer += this.grid[v * this.length + h];
}
buffer += '\n';
}
return buffer;
}
drawAt(x, y, symbol) {
this.grid[y * this.length + x] = symbol;
}
}
const directions = [
'right',
'down',
'left',
'up'
];
function fillGrid(grid) {
let currentLength = grid.length;
let direction = 0;
let x = -1;
let y = 0;
while (currentLength > 0) {
for (let i = 0; i < currentLength; i += 1) {
let symbol = '*';
// Next coordinate.
switch (directions[direction]) {
case 'right':
x += 1;
symbol = '-';
break;
case 'down':
y += 1;
symbol = '|';
break;
case 'left':
x -= 1;
symbol = '-';
break;
case 'up':
y -= 1;
symbol = '|';
break;
}
if (i + 1 === currentLength) {
symbol = '+';
}
grid.drawAt(x, y, symbol);
}
currentLength -= 1;
direction = (direction + 1) % directions.length;
}
}
function main() {
// Check if all arguments are there.
if (process.argv.length >= 3) {
const length = Number.parseInt(process.argv[2]);
const grid = new Grid(length);
fillGrid(grid)
console.log(grid.render());
} else {
console.log(`Error: missing length argument.`);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment