Skip to content

Instantly share code, notes, and snippets.

@azamanaza
Created September 24, 2019 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azamanaza/6ea94b80a07046fa5fff06cfee400f19 to your computer and use it in GitHub Desktop.
Save azamanaza/6ea94b80a07046fa5fff06cfee400f19 to your computer and use it in GitHub Desktop.
code to draw a fibo-like spiral
const rangeSum = n => ((n * (n + 1)) / 2) - 1;
const getMaxRange = pxCt => {
let currRange = 2;
while(pxCt > rangeSum(currRange)) {
currRange++;
}
return currRange;
};
const changeDirection = currDirection => {
switch(currDirection) {
case 'down':
return 'right';
case 'right':
return 'up';
case 'up':
return 'left';
case 'left':
default:
return 'down';
}
}
const makeGrid = (pxCt, px = '*') => {
let currRange = getMaxRange(pxCt);
const height = currRange % 2 === 0 ? currRange : currRange - 1;
const width = currRange % 2 === 0 ? currRange - 1 : currRange;
const grid = new Array(height).fill().map(x => new Array(width).fill(''));
let x = Math.floor((height - 1) / 2);
let y = Math.floor((width - 1) / 2);
let i = 1;
let currDirection = 'down';
let turns = 2;
let turnAtStep = 3;
while(i <= pxCt) {
grid[x][y] = i;
i++;
if (turnAtStep == i) {
currDirection = changeDirection(currDirection);
turnAtStep = turnAtStep + turns;
turns++;
}
switch(currDirection) {
case 'down':
x++;
break;
case 'right':
y++;
break;
case 'up':
x--;
break;
case 'left':
y--;
break;
}
}
return grid;
}
console.table(makeGrid(121))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment