class Graph {
constructor() {
this.nodes = {};
}
addNode(node) {
this.nodes[node] = this.nodes[node] || [];
}
contains(node) {
return Boolean(this.nodes[node]);
}
removeNode(node) {
if (this.contains(node)) {
delete this.nodes[node];
}
}
hasEdge(fromNode, toNode) {
if (this.contains(fromNode) && this.contains(toNode)) {
if (
this.nodes[fromNode].includes(toNode) &&
this.nodes[toNode].includes(fromNode)
)
return true;
}
return false;
}
addEdge(fromNode, toNode) {
this.nodes[fromNode].push(toNode);
this.nodes[toNode].push(fromNode);
}
removeEdge(fromNode, toNode) {
if (this.contains(fromNode) && this.contains(toNode)) {
if (this.hasEdge(fromNode, toNode)) {
const toInFromIdx = this.nodes[fromNode].indexOf(toNode);
const fromInToIdx = this.nodes[toNode].indexOf(fromNode);
this.nodes[fromNode].splice(toInFromIdx, 1);
this.nodes[toNode].splice(fromInToIdx, 1);
}
}
}
}
Graph {
nodes: {
'1': [ 2 ],
'2': [ 1, 7 ],
'3': [ 7, 4 ],
'4': [ 3, 5 ],
'5': [ 4 ],
'6': [ 7 ],
'7': [ 2, 3, 6 ]
}
}
nodes 라는 객체의 키를 가진 형태
해당 노드가 없다면 빈 배열의 객체 값을 가진 형태 생성
해당 노드를 가지고 있나 체크
노드가 존재한다면 해당 노드를 삭제
let o = {
x:1,
y:2
}
delete o.x
o //{y: 2}
객체 o의 프로퍼티가 삭제된다.
간선을 가지고 있는지 체크
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true
두 노드 사이의 간선 추가
두 노드 사이의 간선 제거
1) 두 노드 존재 확인 => contains
2) 사이의 간선 존재 확인 => hasEdge
3) 객체 값에 존재하는 인덱스 번호 확인
4) 해당 인덱스 번호 splice를 통해 제거
단방향을 하고 싶으면 addEdge 코드에서 push 한쪽을 지운다