Last active
December 17, 2015 03:09
-
-
Save nicl/5541327 to your computer and use it in GitHub Desktop.
Convert data table string into usable form
This file contains 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
/** | |
* Convert a dataTable string representation into a List of Maps. For example: | |
* | |
* | x | y | | |
* | 1 | a is | | |
* | 2 | b does | | |
* | |
* Becomes: | |
* | |
* List(Map(x -> 1, y -> "a is"), Map(x -> 2, y -> "b does")) | |
*/ | |
def tableFromString(data: String): List[Map[String, String]] = { | |
def trimEach(seq: Array[String]): Array[String] = seq map { _.trim } | |
val lines = data split("\n") map { _.trim } map { _.drop(1) } map { _.dropRight(1) } | |
// split into lines, then for each remove surrounding whitespace and '|' chars | |
val cellsByLine = lines map { _.split('|') } map trimEach | |
val headerCells = cellsByLine.head | |
val rowCells = cellsByLine.tail | |
rowCells.toList map { row => headerCells.zip(row).toMap } | |
} |
UPDATE: this now handles whitespace correctly so the previous comment can be ignored.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, this is not an exact equivalent of data tables. For example, at the moment this strips out all whitespace from the table. In the following example:
'my value' will become 'myvalue'.