class BiGraph {
constructor(a_type, b_type){
this.a_type = a_type;
this.b_type = b_type;
this.nodes = {
[a_type]: new Map(),
[b_type]: new Map(),
};
}
add_node({id, type, ...other_props}){
this.nodes[type].set(
id,
new Node(id, type, other_props)
);
return this;
};
add_nodes(node_arr){
node_arr.forEach(node => this.add_node(node));
return this;
};
add_edge(edge){
const [a_node, b_node] = [this.a_type, this.b_type].map(type => {
const id = edge[type];
const node_does_not_exist = !this.nodes[type].has(id);
if(node_does_not_exist){
this.add_node({id, type});
}
return this.nodes[type].get(id);
});
Node.new_edge(a_node, b_node);
return this;
};
add_edges(edge_arr){
edge_arr.forEach(edge => this.add_edge(edge));
return this;
}
get edges(){
let all_edges = [];
this.nodes[this.a_type].forEach(a_node =>
a_node.edges.forEach(({node: b_node, count}) =>
all_edges.push({
[`${this.a_type}_id`]: a_node.id,
[`${this.b_type}_id`]: b_node.id,
[this.a_type]: a_node,
[this.b_type]: b_node,
count: count,
})
)
);
return all_edges
}
get_nodes(type){
return Array.from(this.nodes[type].values());
}
get all_nodes(){
return [...this.get_nodes(this.a_type), ...this.get_nodes(this.b_type)];
}
get num_nodes(){
const n_a_nodes = this.nodes[this.a_type].size;
const n_b_nodes = this.nodes[this.b_type].size
return {
[this.a_type]: n_a_nodes,
[this.b_type]: n_b_nodes,
all: n_a_nodes + n_b_nodes,
}
}
static create(a_type, b_type){
return new this(a_type, b_type)
}
}