Skip to content

Instantly share code, notes, and snippets.

@dkowis
Created July 15, 2015 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkowis/64f4efad4fe7bb80a47c to your computer and use it in GitHub Desktop.
Save dkowis/64f4efad4fe7bb80a47c to your computer and use it in GitHub Desktop.
This is all I'd do, honestly
private def getPreferredHeader(headerName: String, getFun: String => List[String]): List[String] = {
case class HeaderValue(headerValue: String) {
val value = headerValue.split(";").head
val quality = {
try {
val headerParameters: Array[String] = headerValue.split(";").tail
val qualityParameters: Option[String] = headerParameters.find(param => "q".equalsIgnoreCase(param.split("=").head.trim))
qualityParameters.map(_.split("=", 2)(1).toDouble).getOrElse(1.0)
} catch {
case e: NumberFormatException => throw new QualityFormatException("Quality was an unparseable value", e)
}
}
}
getFun(headerName) match {
case Nil => Nil
case nonEmptyList =>
nonEmptyList.map(headerValue => HeaderValue(headerValue)) // split the value and parameters, parse the quality
.groupBy(_.quality) // group by quality
.maxBy(_._1) // find the highest quality group
._2 // get the list of highest quality values
.map(_.value) // return a list of just the values
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment