Skip to content

Instantly share code, notes, and snippets.

@itszero
Created May 8, 2013 20:04
Show Gist options
  • Save itszero/5543218 to your computer and use it in GitHub Desktop.
Save itszero/5543218 to your computer and use it in GitHub Desktop.
Scala tutorial question
/* render a tweet using entities: for example
* val e = Entity(10, 21, """<a href="https://twitter.com/search/?q=%23ScalaIntro">#ScalaIntro</a>""")
* val entitites = Set(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 = {
var sb = new StringBuilder(text)
val sortedEntities = entities.sortWith((x: Entity, y: Entity) => x.start < y.start)
var offset = 0
for (entity <- sortedEntities) {
sb.replace(entity.start + offset, entity.end + offset, entity.html)
offset += entity.html.length - (entity.end - entity.start)
}
sb toString
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment