Skip to content

Commit 2b3ff59

Browse files
committed
Rewrite relative method for json pointer
1 parent 95871df commit 2b3ff59

File tree

1 file changed

+14
-8
lines changed
  • src/commonMain/kotlin/io/github/optimumcode/json/pointer

1 file changed

+14
-8
lines changed

src/commonMain/kotlin/io/github/optimumcode/json/pointer/extensions.kt

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -72,17 +72,23 @@ public operator fun JsonPointer.plus(otherPointer: JsonPointer): JsonPointer {
7272
* @throws IllegalArgumentException when [other] is an empty pointer
7373
*/
7474
public fun JsonPointer.relative(other: JsonPointer): JsonPointer {
75-
if (this is EmptyPointer) {
75+
if (this !is SegmentPointer) {
7676
return other
7777
}
78-
require(other !is EmptyPointer) { "empty pointer is not relative to any" }
79-
val currentValue = this.toString()
80-
val otherValue = other.toString()
81-
val relative = otherValue.substringAfter(currentValue)
82-
return if (relative == otherValue) {
83-
other
78+
require(other is SegmentPointer) { "empty pointer is not relative to any" }
79+
var currentValue: JsonPointer = this
80+
var otherValue: JsonPointer = other
81+
while (currentValue is SegmentPointer && otherValue is SegmentPointer) {
82+
if (currentValue.propertyName != otherValue.propertyName) {
83+
return other
84+
}
85+
currentValue = currentValue.next
86+
otherValue = otherValue.next
87+
}
88+
return if (currentValue is EmptyPointer) {
89+
otherValue
8490
} else {
85-
JsonPointer(relative)
91+
other
8692
}
8793
}
8894

0 commit comments

Comments
 (0)