Skip to content

Instantly share code, notes, and snippets.

@travisbrown
Last active December 19, 2015 08:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travisbrown/5923993 to your computer and use it in GitHub Desktop.
Save travisbrown/5923993 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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