Undirected Graph - ES2015

by Danny Michaelis

Babel + JSX

class Node {
  constructor( key ) {
    this.key = key;
    this.parent = null;
    this.distance = Infinity;
    this.adjacentsList = {};
  }
  
  get adjacents() {
    return Object.keys(this.adjacentsList).map(a => this.adjacentsList[a]);
  }

  removeAdjacent( node ) {
    if ( this.adjacentsList[ node.key ] ) {
      delete this.adjacentsList[ node.key ]
    }
  }

  addAdjacent(node) {
    if ( !this.adjacentsList[ node.key ] ) {
      this.adjacentsList[ node.key ] = node;
    }
  }
}

class Station extends Node {
  constructor( x, y, value = null ) {
    super( JSON.stringify( { x, y } ) )
    this.x = x;
    this.y = y
    this.value = value;
  }
  
  get val() {
    return value
  }
  set val(val) {
    this.value = val;
  }
  get up() {
    return this.adjacentsList[JSON.stringify({
      x,
      y: y - 1
    })];
  }
  get down() {
    return this.adjacentsList[JSON.stringify({
      x,
      y: y + 1
    })];
  }
  get left() {
    return this.adjacentsList[JSON.stringify({
      x: x - 1,
      y
    })];
  }
  get right() {
    return this.adjacentsList[JSON.stringify({
      x: x + 1,
      y
    })];
  }
}

class Graph {
  constructor() {
    this.nodes = {};
  }
  addNode(node) {
    if (!this.nodes[node.key]) {
      this.nodes[node.key] = node;
    }
  }

  getNode(node) {
    if (node instanceof Node) {
      return this.nodes[node.key];
    } else {
      return this.nodes[node];
    }
  }

  addEdge(start, end) {
    var startNode = this.getNode(start),
      endNode = this.getNode(end);
    if (!startNode) startNode = new Node(start);
    if (!endNode) endNode = new Node(end);
    startNode.addAdjacent(endNode);
    endNode.addAdjacent(startNode);
    this.addNode(startNode);
    this.addNode(endNode);
  }

  removeNode(node) {
    const
      dead = this.getNode(node),
      adjacents = dead.adjacents();
    for (const n of adjacents) {
      n.removeAdjacent(dead);
    }
    delete this.nodes[dead.key];

  }

  resetNodes() {
    for...