Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
object Trimmed {
val Stop = ".*\\b(a|an|the|to|of|as|in|with|for)$".r
val Fine = "(.+\\.)$".r
val Punc = "(.+)[,;:]$".r
}
class Trimmed(size: Int) {
def unapply(s: String) = s.replaceAll("\\s+", " ") match {
case res if res.size <= size => Some(res)
case res => res.split(' ').inits.map(_ mkString " ").flatMap {
case Trimmed.Stop(_) => None
case Trimmed.Fine(prefix) => Some(prefix)
case Trimmed.Punc(prefix) => Some(prefix + "...")
case prefix => Some(prefix + "...")
}.dropWhile(_.size > size).toList.headOption
}
}
object Tweetable extends Trimmed(140)
val Tweetable(phrase1) = """Egypt’s military on Wednesday ousted Mohamed Morsi,
the nation’s first freely elected president, suspending the Constitution,
installing an interim government and insisting it was responding to the
millions of Egyptians who had opposed the Islamist agenda of Mr. Morsi and
his allies in the Muslim Brotherhood.
"""
val Tweetable(phrase2) = """Leslie James Pickering noticed something odd in his
mail last September: A handwritten card, apparently delivered by mistake,
with instructions for postal workers to pay special attention to the letters
and packages sent to his home.
"""
@travisbrown

This comment has been minimized.

Copy link
Owner Author

@travisbrown travisbrown commented Jul 4, 2013

Note that the behavior is slightly different from Joe Wicentowski's XQuery version, which may produce results that are longer than the target length after the ellipsis is added. Here the result is guaranteed not to be longer than the target length.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.