Undirected Graph - ES2015

by Hari Menon

JavaScript

'use strict';
// Queue
class Queue {
    constructor() {
        this.items = [];
    }

    get size() {
        return this.items.length;
    }

    get isEmpty() {
        return this.items.length === 0;
    }

    enqueue(item) {
        this.items.push(item);
    }

    dequeue() {
        return !this.isEmpty ? this.items.shift() : undefined;
    }

    peek() {
        return !this.isEmpty ? this.items[this.items.length - 1] : undefined;
    }
}

// Node
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]);
    }

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

// Graph
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);
    }

    resetNodes() {
        for (let n of this.nodes) {
            n.distance = Infinity;
            n.parent = null;
        }
    }
    
    printDistances() {
        console.log(Object.keys(this.nodes).map(n => n.key + ' : ' + n.distance).join(', '));
    }
}