Given a 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 any better way of doing this?
UPDATE
Following the comments to this question, I have changed the code to address a few issues:
- Over splitting
- Empty input
- Other separators
Ended up with:
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 chose to use reduceOption over changing the signature to commonPrefix(path: String, paths: String*), because then I can use the following syntax:
val paths = Seq("/a/b", "/a/c")
val baseDir = commonPrefix(paths:_*)
Looks OK to me now.
I guess there is no existing Java/Scala library that already does all this, right?