StringBuilder does not compile in JS


#1

Hi

Im using StringBuilder.delete that does compile & run in the cli.
The same code will not compile for Kotlin-JS, delete is not existing here!
Instead, the use of removeRange is suggested but that has complete different behavior. Thus i can not use the code without re writing it completely.

Any hints on that?


#2

I have just took quick look at Java implementation of StringBuilder and it is basically ArrayList<Char>. Somehow I always thought it was ArrayList<String> that is getting concatenated to single String in toString().
I would suggest implementing fully mutable custom StringBuilder and using it since kotlin implementation for some reason allows only appends.

It is easy to make. Took me about 7mins

class AwesomeBuilder {
    // this is not optimal. use js arrays instead of mutableList.
    private var chars = mutableListOf<Char>()

    val length = chars.size

    fun append(value: Int) = append(value.toString())
    fun append(str: String) = chars.addAll(str.asIterable())

    fun delete(startIndex: Int, endIndex: Int) {
        if (endIndex < startIndex)
            throw IndexOutOfBoundsException("End index ($endIndex) is less than start index ($startIndex).")

        if (endIndex == startIndex)
            return

        chars = mutableListOf<Char>().apply {
            addAll(chars.subList(0, startIndex))
            addAll(chars.subList(endIndex, length))
        }
    }

    override fun toString(): String {
        // this is really slow.
        return chars.joinToString(separator = "")
    }
}