I would prefer inverting this `if` statement:

    if (sharedPrefix.length() <= contextLength) {
      return sharedPrefix
    }
    ...

That way, the simplest part of the code is taken care of up front.