JSFiddle - React, Tailwind, and code Playground
by dp0ch
JavaScript
// Point == [x, y]:
function closestPoint(position, points) {
return points
.reduce((min, point) => {
console.log(min, point)
return distance(position, min) > distance(position, point) ? point : min;
}, 0);
}
function distance(p1, p2) {
return Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1]);
}
function pointMap(points) {
return points.reduce((acc, point) => ({
...acc,
[JSON.stringify(point)] : true,
}), {});
}
function findShortest(position, map) {
const visited = {};
const queue = [position];
while (queue.length > 0) {
const p = queue.shift();
const serializedP = JSON.stringify(p);
if(map[serializedP]) return p;
visited[serializedP] = true;
const right = [p[0] + 1, p[1]];
const left = [p[0] - 1, p[1]];
const up = [p[0], p[1] + 1];
const down = [p[0], p[1] - 1];
if(!visited[JSON.stringify(right)]) queue.push(right);
if(!visited[JSON.stringify(left)]) queue.push(left);
if(!visited[JSON.stringify(up)]) queue.push(up);
if(!visited[JSON.stringify(down)]) queue.push(down);
}
}
const m = pointMap([[1, 2], [2, 1], [5, 5]]);
console.log(document.body);
//document.write(findShortest([0, 0], m));