Permalink
Browse files

Made toJsCmd for CmdPair tail recursive. Closes #1288

  • Loading branch information...
1 parent 35ea02d commit 3036ba2d1e99263f98d7fd904097f5ecb1408e4d @dpp dpp committed Jul 2, 2012
Showing with 12 additions and 11 deletions.
  1. +12 −11 web/webkit/src/main/scala/net/liftweb/http/js/JsCommands.scala
@@ -790,19 +790,20 @@ object JsCmds {
implicit def jsExpToJsCmd(in: JsExp) = in.cmd
case class CmdPair(left: JsCmd, right: JsCmd) extends JsCmd {
- def toJsCmd = {
- val sb = new StringBuilder
- append(sb, this)
- sb.toString
- }
+ import scala.collection.mutable.ListBuffer;
- private def append(sb: StringBuilder, cmd: JsCmd) {
- cmd match {
- case CmdPair(l, r) => append(sb, l)
- sb.append('\n')
- append(sb, r)
+ def toJsCmd: String = {
+ val acc = new ListBuffer[JsCmd]()
+ appendDo(acc, left :: right :: Nil)
+ acc.map(_.toJsCmd).mkString("\n")
+ }
- case c => sb.append(c.toJsCmd)
+ @scala.annotation.tailrec
+ private def appendDo(acc: ListBuffer[JsCmd], cmds: List[JsCmd]) {
+ cmds match {
+ case Nil =>
+ case CmdPair(l, r) :: rest => appendDo(acc, l :: r :: rest)
+ case a :: rest => acc.append(a); appendDo(acc, rest)
}
}
}

3 comments on commit 3036ba2

@Shadowfiend
Member

Random curiosity: why split this into appendDo with a ListBuffer and then mkString? Is there an advantage over doing basically what appendDo is doing but with StringBuffers instead and producing a String result? Or is it just for clarity/style purposes?

@dpp
Member
dpp commented on 3036ba2 Jul 2, 2012

I had to turn the JsCmds into a List and then a ListBuffer (in effect flattening them) before I could apply an operation, otherwise the method would not be tail recursive.

@Shadowfiend
Member

Oh right! Awesome, thanks for the clarification :)

Please sign in to comment.