Skip to content
Prev Previous commit
Next Next commit
StringRope on List
  • Loading branch information
MaxGekk committed Dec 29, 2018
commit 0a36a26a8bdbace64be8260189475014cb1c0e27
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,26 @@ object StringUtils {
}
funcNames.toSeq
}

class StringRope {
private var list = List.empty[String]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use a ListBuffer or an ArrayBuffer here. Those have (amortized) constant time appends and do not force you to reverse the collection when building the string.

Copy link
Member Author

@MaxGekk MaxGekk Dec 29, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I supposed this reverse is relatively cheap O(n). Coping a string would be more expensive than adding element to the head of list inside of the reverse() method. In any case, need to traverse over the list in toString.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I replaced List by ArrayBuffer

private var length: Int = 0

def append(s: String): Unit = {
list = s :: list
length += s.length
}

override def toString: String = {
val buffer = new StringBuffer(length)
var reversed = list.reverse

while (!reversed.isEmpty) {
buffer.append(reversed.head)
reversed = reversed.tail
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why the new line?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for beauty

buffer.toString
}
}
}