Skip to content

Instantly share code, notes, and snippets.

@yllan
Forked from itszero/gist:5543218
Last active December 17, 2015 03:39
Show Gist options
  • Save yllan/5545188 to your computer and use it in GitHub Desktop.
Save yllan/5545188 to your computer and use it in GitHub Desktop.
/* render a tweet using entities: for example
* val e = Entity(10, 21, """<a href="https://twitter.com/search/?q=%23ScalaIntro">#ScalaIntro</a>""")
* val entities = Seq(e)
* render("I love my #ScalaIntro exercises!", entities)
* should result in
* """I love my <a href="https://twitter.com/search/?q=%23ScalaIntro">#ScalaIntro</a> exercises!"""
* The "start" and "end" fields of an Entity refer to the indices in the
* original string to be substituted with the html field; you may assume
* that these indices are all non-overlapping.
*/
case class Entity(start: Int, end: Int, html: String)
// note: the entities are not guaranteed to be in any particular order
def render(text: String, entities: Seq[Entity]): CharSequence = {
val sortedEntities = entities.sortWith((x: Entity, y: Entity) => x.start < y.start)
def renderIter(buffer: StringBuilder, start: Int, end: Int, sortedEntities: Seq[Entity]): StringBuilder = sortedEntities match {
case Seq() => buffer.append(text.slice(start, end))
case e +: es => {
buffer.append(text.slice(start, e.start)).append(e.html)
renderIter(buffer, e.end, end, es)
}
}
renderIter(new StringBuilder, 0, text.length, sortedEntities).toString
}
// Oppa Functional Style
def render(text: String, entities: Seq[Entity]): CharSequence = {
def renderIter(start: Int, end: Int, entities: Seq[Entity]): String = entities match {
case Seq() => text.slice(start, end)
case e +: es => {
val (lesser, greater) = es.partition(_.start < e.start)
renderIter(start, e.start, lesser) + e.html + renderIter(e.end, end, greater)
}
}
renderIter(0, text.length, entities)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment