Skip to content

Instantly share code, notes, and snippets.

@thomasfoster96
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasfoster96/b419f98cfb4bf9a4f4f9 to your computer and use it in GitHub Desktop.
Save thomasfoster96/b419f98cfb4bf9a4f4f9 to your computer and use it in GitHub Desktop.
Data structures.
class Graph {
adjList = new Map()
constructor(iterable, directed = true){
for(let node of iterable){
this.adjList.set(node, new Map());
}
}
adjacent(x, y){
if(this.adjList.has(x)){
if(this.adjList.get(x).has(y)){
if(this.asjList.get(x).get(y).size > 0){
return true;
}
}
}
return false
}
neighbours(x){
if(this.adjList.get(x)){
return new Set([for ([node] of this.adjList.get(x)) node]);
}
return new Set([]);
}
* edges(){
const done = new Set();
for(let [, value] of this.adjList){
for(let [, edges] of value){
for(let edge of edges){
if(!done.has(edge)){
done.add(edge);
yield edge;
}
}
}
}
}
* nodes(){
for(let [key] of this.adjList){
yield key;
}
}
addEdge(to, from, edge){
if(this.adjList.has(to)){
if(!this.adjList.get(to).has(from)){
this.adjList.get(to).set(from, new Set())
}
this.adjList.get(to).get(from).add(edge);
if(!this.directed){
if(!this.adjList.get(from).has(to)){
this.adjList.get(from).set(to, new Set())
}
this.adjList.get(from).get(to).add(edge);
}
}
return this;
}
addNode(node){
if(!this.adjList.has(node)){
this.adjList.set(node, new Map());
}
return this;
}
getEdges(to, from){
if(this.adjList.has(to)){
if(this.adjList.get(to).has(from)){
new Set(this.adjList.get(to).get(from));
}
}
return new Set([]);
}
removeEdge(to, from, edge){
if(this.adjList.has(to)){
if(this.adjList.get(to).has(from)){
this.asjList.get(to).get(from).remove(edge);
}
}
return this;
}
removeNode(node){
this.adjList.delete(node);
for (let [key] of this.adjList){
this.adjList.get(key).delete(node);
}
return this;
}
* [Symbol.iterator](){
for(let [key] of this.adjList){
yield key;
}
}
get [Symbol.toStringTag](){
return "Graph";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment