Undirected Graph - ES2015
by Danny Michaelis
Babel + JSX
class Node {
constructor( key ) {
this.key = key;
this.parent = null;
this.distance = Infinity;
this.adjacentsList = {};
}
reconstruct( { key, parent, distance, adjacentsList } ) {
this.key = key;
this.parent = parent;
this.distance = distance;
this.adjacentsList = adjacentsList;
return this;
}
toJSON() {
return Object.assign( {}, this, { adjacentsList: Object.keys(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 Square 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 = {};
}
reconstruct( nodes ) {
return 'You have to Impliment this';
}
toJSON() {
return 'You have to Impliment this';
}
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 =...