Created
December 22, 2017 23:47
-
-
Save skiano/814acd365aed8c64c9bc5c797e5ef9ab to your computer and use it in GitHub Desktop.
walk the coordinates of a grid in a spiral to the center
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// walk around the edges of a grid | |
// and work toward the center | |
// Begin going right. | |
// When you are at an edge or a filled square, turn right. | |
const spiral = (w, h, fn) => { | |
// a map where keys are visited indexes | |
const visited = {} | |
// translations represent increments for: right -> down -> left -> up | |
const translations = [1, w, -1, -w] | |
let direction = 0 | |
let idx = 0 | |
let step = w * h | |
let nextIdx | |
let x | |
let y | |
while (step--) { | |
nextIdx = idx + translations[direction] | |
x = idx % w | |
y = (idx / w) >> 0 | |
if (fn) fn(x, y, idx) | |
if ( | |
visited[nextIdx] || | |
(direction === 2 && x === 0) || | |
(direction === 3 && y === 0) || | |
(direction === 0 && x === w - 1) || | |
(direction === 1 && y === h - 1) | |
) { | |
direction = direction < 3 ? direction + 1 : 0 | |
nextIdx = idx + translations[direction] | |
} | |
visited[idx] = true | |
idx = nextIdx | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment