2023-06-14

 14 Jun 2023

Write a SocialGraph Class

Taken from Execute Program

Write a SocialGraph class with a constructor and two methods.

  • The constructor creates an empty Map.
  • The addFollow method records that user1 follows user2 by updating the map. Note that order matters here
  • The follows method checks for whether user1 follows user2, returning a boolean.

Solution

This is the answer I came up with:

interface SocialGraph {
  map: Map<string, string[]>
}

class SocialGraph {
  constructor() {
    this.map = new Map()
  }

  addFollow(user1: string, user2: string) {
    // If user2 isn't present, create a user2 key in the map
    if (!this.map.has(user2)) {
      this.map.set(user2, [])
    }
    // Get the array of users of user1, and add user1
    this.map.get(user2).push(user1)
  }

  follows(user1: string, user2: string) {
    // If user2 doesn't exist, return false
    if (!this.map.has(user2)) { return false }
    // Otherwise get the array of users of user2, and check if it includes user1
    return this.map.get(user2).includes(user1)
  }
}

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?strictNullChecks=false#code/JYOwLgpgTgZghgYwgAgMoHsHDgGwOJRwAOAFsgN4CwAUMsgLbEBcyAssQDwDOYUoA5gBpkPPiH4BtALoA+GgF8aNBDjhcuaTNnyFSFGnQToQogK4Iw6KAAoAlPtp1kYEsC4A6RkWQBeZCAgAdzZiOwNkRWpwuAATGIAxdBwcdEDrUy5oAEYWUQFhDOgAJlzeAXsqRzoAemrkAEkYZEKoIuQ3EAByMGQiKAhM8GEEfrhIZDhmzNbkAGsIAE92kGcSFC9wumAm6wBCFzdPYncSNXTpotsKzacDjy93TLBz4uFpWxvIp2Ra5DwIHouFBwKCEJboJotDQQqbZYRwEAxCZxWFQLI3O5HIjufgAl6tWzuIgZEj4rIfRyRcIwJIpQJcMmlMRCVElERlcTXKo-OqNVnIGLoAZdHoQAAebjAwn6YFMUBW8BwmRu22Qe0xD1ODJalwqyBlcoVuEyERuvwA8kCoIE3ChcYC1hNQXBwZDptC3a8JojkAg1ghZu0msAeqAVKYYgNUejuQb5atDg97fjLu4wzgIwMyRS6JEqdQjCYelwtLgCMQyH4AsEMFgy7pSbYANw0Et1nQV9yxBK01LWTpwejAKCdYSdABGALAC06zdbpY7pC7cUSyT7A6HI7HWERM7n1Db2nLS+7q7p-cnYGno+QnR3MT3LaiBeMJZwEHcKX41nCEnCh-rTsaTXel+0HYcbwnKc90Ef8F2PEh3GAukGQ3CDt1AB9Z1gxwAMXRDkNSVDL2vMdwJHWwcLoPCEKQ3tQKgq8Zww3dsLg9taMIhj72Y29yLY3D4IbOiQNQnjIJImCaCkexfgkXhTAgYQFKU5BFUyZSoEU4R1NU3SpBoIA

Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated October 9, 2024 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems