Scala - How do I find the base path for two or more paths?

Given the sequence of directory paths, what is the best way to find their most common base directory?

Here is the code I wrote.

 def commonPrefix(paths: String*): String = {
    paths.reduce((left: String, right: String) => {
      left.split('/')
        .zip(right.split('/'))
        .takeWhile((tuple: (String, String)) => tuple._1.equals(tuple._2))
        .map(_._1).mkString("/")
    })
  }

      

Is there a better way to do this?

UPDATE

After comments on this question, I modified the code to address several issues:

  • Over splitting
  • Empty input
  • Other separators

This is done:

def commonPrefix(paths: String*)(implicit separator: Char = '/'): String = {
    paths.map(s => s.split(separator))
      .reduceOption((left: Array[String], right: Array[String]) => {
        left
          .zip(right)
          .takeWhile(tuple => tuple._1.equals(tuple._2))
          .map(_._1)
      }).getOrElse(Array[String]())
      .mkString("/")
  }

      

I decided to use reduceOption

to replace the signature with commonPrefix(path: String, paths: String*)

because then I can use the following syntax:

val paths = Seq("/a/b", "/a/c")
val baseDir = commonPrefix(paths:_*)

      

Everything looks good now.

I think there is no existing Java / Scala library that does all of this already, right?

+3


source to share





All Articles