JSFiddle - React, Tailwind, and code Playground
JavaScript 1.7
class UnionFind {
constructor() {
this.nodes = 0;
this.sizeOf = [];
this.parent = [];
for (let i = 0; i < 10; i++) {
this.nodes++;
this.size[i] = 1;
this.parent[i] = i;
}
}
rootOf = (a) => {
let current = a;
while (this.parent[current] !== current) {
current = this.parent[current];
}
this.compress(a, current);
return current;
};
compress = (a, root) => {
let curr = a;
while (this.parent[current] !== current) {
const next = this.parent[current];
this.parent[current] = root;
curr = next;
}
return current;
};
union = (a, b) => {
const ap = rootOf(a);
const bp = rootOf(b);
if (this.sizeOf[ap] < this.sizeOf[bp]) {
this.parent[ap] = bp;
this.sizeOf[bp] += this.sizeOf[ap];
this.compress(a, bp);
} else {
this.parent[bp] = ap;
this.sizeOf[ap] += this.sizeOf[bp];
this.compress(b, ap);
}
this.nodes--;
};
}