disjoints sets

mail@pastecode.io avatarunknown
javascript
a month ago
1.5 kB
3
Indexable
Never
class Friend {
  constructor(email) {
    this.email = email;
    this.friends = [];
    this.bestFriend = null;
  }

  addFriendship(friend) {
    this.friends.push(friend);
    friend.friends.push(this);

    const bestFr = this.getBestFriend();
    // console.log('log best f: ', bestFr?.email);
    friend.setBestFriend(bestFr);
  }

  canBeConnected(friend) {
    // Your code goes here
    if (this.getBestFriend()?.email === friend.getBestFriend()?.email) return true;
    return false;
  }
  getBestFriend() {
    if (!this.bestFriend) return this;
    const bestFr = this.bestFriend.getBestFriend();
    this.bestFriend = bestFr;
    return bestFr;
  }
  setBestFriend(bestFr) {
    if (!this.bestFriend) {
      if (this.email === bestFr.email) return ;
      this.bestFriend = bestFr;
      return;
    }
    this.bestFriend.setBestFriend(bestFr);
    this.bestFriend = bestFr;
  }
}

const a = new Friend('A');
const b = new Friend('B');
const c = new Friend('C');

a.addFriendship(b);
b.addFriendship(c);

console.log(a.canBeConnected(c));

// const a = new Friend('A');
// const b = new Friend('B');
// const c = new Friend('C');
// const d = new Friend('D');

// a.addFriendship(b);
// b.addFriendship(c);
// c.addFriendship(d);
// a.addFriendship(a);

// console.log(a.getBestFriend()?.email);
// console.log(b.getBestFriend()?.email);
// console.log(c.getBestFriend()?.email);
// console.log(d.getBestFriend()?.email);

// console.log(a.canBeConnected(d));