I am using Okio in Kotlin/Native and I would like to check if one path is inside another path.
Although there is a equal/greater than/less than operator, it looks like it only compares the length.
Example:
"/a/b/c/d".toPath().startsWith("/a/b/c".toPath()) // should return true
"/a/b/d/d".toPath().startsWith("/a/b/c".toPath()) // should return false
But startsWith does not exist.
Kotlin/JVM supports this via Java: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/starts-with.html
I have created this extension function which implements
startsWithas described in the question:It first checks if the
otherpath has more segments (or components) thanthispath which would already mean they don't match since/a/b/ccan never start with/a/b/c/d(or even/1/2/3/4).If the segment count of
otheris the same or less, it proceeds with slicingthisinto as many segments asotherhas so that any sub-entries are ignored.Then, it filters the sliced segments of
thisthat don't match by using the same index for accessing the segments ofother.Now we have a list of segments that don't match on the same index. By checking if the list
isEmpty(), we now have the conclusion of whetherthisstartsWithother(you can turn this into an infix if you want.).Passing test: