a star in javascript

To implement the A* algorithm in JavaScript, you first need to represent your graph as an adjacency list, an array of arrays where each sub-array represents the edges that emanate from a node. Once you have your graph in this format, you can implement the A* algorithm by initializing a priority queue with the starting node, setting the cost of the starting node to 0, and adding it to a set of visited nodes. Then, while the priority queue is not empty, you dequeue the node with the lowest cost and iterate over its neighbors. For each neighbor, you calculate its cost and heuristic value, and if it has not already been visited, add it to the priority queue. Finally, once you reach the target node, you can reconstruct the path by tracing back from the target node to the starting node, keeping track of the nodes that led to each visited node. Here's an implementation of the A* algorithm in JavaScript:

index.tsx
function aStar(start, target, graph) {
  const queue = new PriorityQueue();
  const visited = new Set();
  const costs = {};
  const previous = {};

  // Initialize starting node
  queue.enqueue(start, 0);
  visited.add(start);
  costs[start] = 0;

  while (!queue.isEmpty()) {
    const current = queue.dequeue();

    if (current === target) {
      return reconstructPath(start, target, previous);
    }

    graph[current].forEach(neighbor => {
      const cost = costs[current] + neighbor.cost;
      if (!visited.has(neighbor.node) || cost < costs[neighbor.node]) {
        visited.add(neighbor.node);
        costs[neighbor.node] = cost;
        const priority = cost + heuristic(neighbor.node, target);
        queue.enqueue(neighbor.node, priority);
        previous[neighbor.node] = current;
      }
    });
  }

  // Target node is not reachable from start node
  return null;
}

function reconstructPath(start, target, previous) {
  const path = [];
  let current = target;

  while (current !== start) {
    path.push(current);
    current = previous[current];
  }

  path.push(start);
  return path.reverse();
}

function heuristic(node, target) {
  // Manhatten distance heuristic
  const [x1, y1] = node.split(',');
  const [x2, y2] = target.split(',');
  return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}

class PriorityQueue {
  constructor() {
    this.items = [];
  }

  enqueue(item, priority) {
    this.items.push({ item, priority });
    this.items.sort((a, b) => a.priority - b.priority);
  }

  dequeue() {
    return this.items.shift().item;
  }

  isEmpty() {
    return this.items.length === 0;
  }
}
1628 chars
73 lines

gistlibby LogSnag