Get the highest role of a user across all the organizations he is member of I have a function that looks like this:

def getMaxUserLevelByUserId(userId: Muid)(
      implicit connection: Connection): Option[OrganizationMembership.Level.Value] = {
    val organizationMemberships = getAllByUserId(userId)

    if (organizationMemberships.exists(_.level == OrganizationMembership.Level.Admin)) {
      Some(OrganizationMembership.Level.Admin)
    } else if (organizationMemberships.exists(_.level == OrganizationMembership.Level.Member)) {
      Some(OrganizationMembership.Level.Member)
    } else if (organizationMemberships.exists(_.level == OrganizationMembership.Level.Guest)) {
      Some(OrganizationMembership.Level.Guest)
    } else {
      None
    }
  }


The gets the highest role of a user across all the organizations he is member of. As you can see, the function is pretty straightforward and works. However, it has a complexity of O(n3). I was wondering if there is a way to get it to O(n) or at least a bit lower?
Well, this is what I did. Not sure if that's the best way to go.

def getMaxUserLevelByUserId(userId: Muid)(
      implicit connection: Connection): Option[OrganizationMembership.Level.Value] = {
    val organizationMemberships = getAllByUserId(userId)

    if (organizationMemberships.nonEmpty) {

      val levelMap = Map(
          OrganizationMembership.Level.Guest -&gt; 0,
          OrganizationMembership.Level.Member -&gt; 1,
          OrganizationMembership.Level.Admin -&gt; 2
      )

      val maxLevel = organizationMemberships.foldLeft(OrganizationMembership.Level.Guest) {
        (level, organizationMembership) =&gt;
          if (levelMap(organizationMembership.level) &gt; levelMap(level)) {
            organizationMembership.level
          } else {
            level
          }
      }

      Some(maxLevel)

    } else {

      None

    }
  }


The idea behind the code above, is the fact that we are iterating through the collection only once, regardless of the collection size. 
The levelMap was created strictly for the reason of easier comparison.

The cool thing about foldLeft in this case is that we don't need to create mutable variables while iterating through the collection and it is actually very short and quite readable code.