Skip to content

Instantly share code, notes, and snippets.

@skiano
Created December 22, 2017 23:47
Show Gist options
  • Save skiano/814acd365aed8c64c9bc5c797e5ef9ab to your computer and use it in GitHub Desktop.
Save skiano/814acd365aed8c64c9bc5c797e5ef9ab to your computer and use it in GitHub Desktop.
walk the coordinates of a grid in a spiral to the center
// 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