I hate string manipulations

This commit is contained in:
Sad Ellie 2023-05-19 17:46:26 +03:00
parent 275485d15a
commit 9444e55d71

View File

@ -43,31 +43,22 @@ class ExpressionTransformer(private val formatterSymbols: FormatterSymbols) : Vi
// original input is "1000" and cursor is placed at the end "1000|" // original input is "1000" and cursor is placed at the end "1000|"
// the formatted is "1,000" where cursor should be? - "1,000|" // the formatted is "1,000" where cursor should be? - "1,000|"
override fun originalToTransformed(offset: Int): Int { override fun originalToTransformed(offset: Int): Int {
val grouping = formatterSymbols.grouping.first() val unformattedSubstr = unformatted.take(offset)
val fixedCursor = unformatted.fixCursor(offset, formatterSymbols.grouping)
// Unformatted always has "." (dot) as a fractional, we can't ues for checking with buffer,
// because it will fail when fractional is "," (comma)
val subString = formatted
.replace(formatterSymbols.grouping, "")
.replace(formatterSymbols.fractional, ".")
.take(offset)
var buffer = "" var buffer = ""
var groupingCount = 0 var groupings = 0
var cursor = 0
// we walk over formatted and stop when it matches unformatted (also counting grouping) run {
while (buffer != subString) { formatted.forEach {
val currentChar = formatted[cursor] when (it) {
if (currentChar == grouping) { formatterSymbols.grouping.first() -> groupings++
groupingCount += 1 formatterSymbols.fractional.first() -> buffer += "."
} else { else -> buffer += it
buffer += currentChar }
if (buffer == unformattedSubstr) return@run
} }
cursor++
} }
return fixedCursor + groupingCount return formatted.fixCursor(buffer.length + groupings, formatterSymbols.grouping)
} }
// Called when clicking formatted text // Called when clicking formatted text