Skip to content
Snippets Groups Projects
Commit 5aedab83 authored by Peter van 't Hof's avatar Peter van 't Hof
Browse files

Added a option to allow fallback on strings

parent 25aaee6e
No related branches found
No related tags found
No related merge requests found
...@@ -90,7 +90,7 @@ object Picard { ...@@ -90,7 +90,7 @@ object Picard {
val header = lines(start).split("\t") val header = lines(start).split("\t")
val content = (for (i <- (start + 1) until end) yield lines(i).split("\t")) val content = (for (i <- (start + 1) until end) yield lines(i).split("\t"))
.map(row => row.map(col => tryToParseNumber(col).getOrElse(col))) .map(row => row.map(col => tryToParseNumber(col, true).getOrElse(col)))
Option((header, content.toList)) Option((header, content.toList))
} else { } else {
......
...@@ -25,13 +25,10 @@ package object utils { ...@@ -25,13 +25,10 @@ package object utils {
* @param funcs one or more conversion functions to apply. * @param funcs one or more conversion functions to apply.
* @return a [[Try]] object encapsulating the conversion result. * @return a [[Try]] object encapsulating the conversion result.
*/ */
def tryToConvert(raw: String, funcs: (String => Any)*): Try[Any] = funcs match { def tryToConvert(raw: String, funcs: (String => Any)*): Try[Any] = {
if (funcs.isEmpty) Try(throw new Exception(s"Can not extract value from string $raw"))
case Seq(firstFunc, otherFuncs @ _*) => else Try(funcs.head(raw))
Try(firstFunc(raw)) .transform(s => Success(s), f => tryToConvert(raw, funcs.tail: _*))
.transform(s => Success(s), f => tryToConvert(raw, otherFuncs: _*))
case Nil => Try(throw new Exception(s"Can not extract value from string $raw"))
} }
/** /**
...@@ -44,16 +41,13 @@ package object utils { ...@@ -44,16 +41,13 @@ package object utils {
* a [[Double]], then a [[BigDecimal]]. * a [[Double]], then a [[BigDecimal]].
* *
* @param raw the string to convert. * @param raw the string to convert.
* @param fallBack Allows also to return the string itself when converting fails, default false.
* @return a [[Try]] object encapsulating the conversion result. * @return a [[Try]] object encapsulating the conversion result.
*/ */
def tryToParseNumber(raw: String) = raw match { def tryToParseNumber(raw: String, fallBack: Boolean = false) = raw match {
case isInteger(i) => tryToConvert(i, x => x.toInt, x => x.toLong, x => BigInt(x))
case isInteger(i) => case isDecimal(f) => tryToConvert(f, x => x.toDouble, x => BigDecimal(x))
tryToConvert(i, x => x.toInt, x => x.toLong, x => BigInt(x)) case _ if fallBack => Try(raw)
case _ => Try(throw new Exception(s"Can not extract number from string $raw"))
case isDecimal(f) =>
tryToConvert(f, x => x.toDouble, x => BigDecimal(x))
case otherwise => Try(throw new Exception(s"Can not extract number from string $raw"))
} }
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment