@@ -15,6 +15,7 @@ import scanner
1515import stream
1616import string
1717import partial
18+ import map
1819
1920
2021/*
@@ -48,6 +49,16 @@ def collectString{ body: => Unit / { emit[Char] } }: String = {
4849 str
4950}
5051
52+ def contains[T](lst: List[T], v: T) {comp: (T, T) => Bool}: Bool = {
53+ var found = false
54+ lst.foreach { x =>
55+ if (comp(x, v)) {
56+ found = true
57+ }
58+ }
59+ return found
60+ }
61+
5162/*
5263---------------------------------------------------
5364--- The following part is written by @jiribenes ---
@@ -238,6 +249,43 @@ def getColumnOf[R](columnName: String) { csv: => R / CsvBuilder }: R / {emit[Str
238249 }
239250}
240251
252+ /// Not in PR, added by myself
253+ ///
254+ /// Get multiple columns by their names
255+ def getColumnsOf[R](columnNames: List[String]) { csv: => R / CsvBuilder }: R / {emit[Map[String, String]], Exception[WrongFormat]} = {
256+ with on[MissingValue].panic() // should never happen
257+ val compFuncString = box {(x: String, y: String) => if (x < y) Less() else if (x > y) Greater() else Equal()}
258+ val compFuncInt = box {(x: Int, y: Int) => if (x < y) Less() else if (x > y) Greater() else Equal()}
259+ var columnIdsMap = empty[Int, String](compFuncInt)
260+ try csv() with CsvBuilder {
261+ def rows[R]() = resume { {r} =>
262+ var currentColumn = 0
263+ var resultMap: Map[String, String] = empty[String, String](compFuncString)
264+ val ret = try r() with RowBuilder {
265+ def cell(s) = {
266+ currentColumn = currentColumn + 1
267+ if (not(columnIdsMap.contains(currentColumn)) and columnNames.contains(s.trim()) {(x, y) => x == y}) {
268+ columnIdsMap = columnIdsMap.put(currentColumn, s.trim())
269+ } else if (columnIdsMap.contains(currentColumn)) {
270+ val colName = columnIdsMap.get(currentColumn).value()
271+ resultMap = map::put(resultMap, colName, s.trim())
272+ }
273+ resume(())
274+ }
275+ }
276+ if (not(resultMap.isEmpty())) {
277+ do emit(resultMap)
278+ }
279+
280+ // it's the first iteration and we haven't found a column yet!
281+ if (columnIdsMap.size() < columnNames.size()) {
282+ wrongFormat("Header doesn't have the given column name: " ++ columnNames.show())
283+ }
284+ ret
285+ }
286+ }
287+ }
288+
241289
242290def main() = {
243291 with on[WrongFormat].report
0 commit comments