diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/jsMain/kotlin/io/Path.kt | 23 | ||||
-rw-r--r-- | src/jsTest/kotlin/io/PathTest.kt | 11 |
2 files changed, 20 insertions, 14 deletions
diff --git a/src/jsMain/kotlin/io/Path.kt b/src/jsMain/kotlin/io/Path.kt index 20e4a90..241c559 100644 --- a/src/jsMain/kotlin/io/Path.kt +++ b/src/jsMain/kotlin/io/Path.kt @@ -60,21 +60,16 @@ sealed class Path { fun relativize(path: Path): Relative = when (path) { is Relative -> path is Absolute -> { - var commonPrefix = true - val partList = mutableListOf<String>() - var returns = 0 - for ((idx, part) in path.parts.withIndex()) { - if (idx < this.parts.size) { - if (this.parts[idx] == part && commonPrefix) { - continue - } else { - commonPrefix = false - returns++ - } - } - partList.add(part) + var idx = 0 + while (idx < path.parts.size && idx < parts.size && path.parts[idx] == parts[idx]) { + idx++ } - Relative(List(returns) { ".." } + partList) + val returns = if (idx < parts.size) { + parts.size - idx + } else { + 0 + } + Relative(List(returns) { ".." } + path.parts.subList(idx, path.parts.size)) } } } diff --git a/src/jsTest/kotlin/io/PathTest.kt b/src/jsTest/kotlin/io/PathTest.kt index 174c2b2..9ba8a9e 100644 --- a/src/jsTest/kotlin/io/PathTest.kt +++ b/src/jsTest/kotlin/io/PathTest.kt @@ -90,4 +90,15 @@ class PathTest : FunSpec({ } } } + test("relaitivization works") { + forAll( + row("/a/b", "/a", ".."), + row("/a", "/a/b", "b"), + row("/a/b", "/a/c", "../c"), + ) { a, b, c -> + assertSoftly { + Path.of(a).shouldBeTypeOf<Path.Absolute>().relativize(Path.of(b)) shouldBe Path.of(c) + } + } + } }) |