Last active
December 19, 2015 08:09
-
-
Save travisbrown/5923993 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.