Skip to content
GitLab
Projects
Groups
Snippets
Help
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Open sidebar
Andrey Vetlugin
groovy-csv-exercise
Commits
84625e20
Commit
84625e20
authored
Jan 24, 2018
by
Andrey Vetlugin
Browse files
Initial commit
parents
Changes
3
Hide whitespace changes
Inline
Side-by-side
Showing
3 changed files
with
85 additions
and
0 deletions
+85
-0
data.csv
data.csv
+3
-0
reader.groovy
reader.groovy
+44
-0
writer.groovy
writer.groovy
+38
-0
No files found.
data.csv
0 → 100644
View file @
84625e20
"name","email","company"
"Andrey","andrey@cc.de",""
"Sems","sems@cc.de","cc"
reader.groovy
0 → 100644
View file @
84625e20
#
!
/usr/
bin
/
env
groovy
String
unescape
(
String
escaped
)
{
return
escaped
}
// TODO implement this
//assert 'asdf' == unescape('"asdf"')
//assert 'as"df' == unescape('"as""df"')
//assert "" == '""'
assert
unescape
(
'asdf'
)
==
'asdf'
List
<
String
>
splitLine
(
String
line
)
{
return
line
.
split
(
/,/
)
}
assert
splitLine
(
'a,b,c'
)
==
[
'a'
,
'b'
,
'c'
]
List
<
String
>
lines
=
new
File
(
'data.csv'
).
readLines
()
Set
<
String
>
headers
=
[]
// get headers
splitLine
(
lines
.
remove
(
0
)).
each
{
headers
.
add
(
it
)
}
println
headers
// TODO get lines
// TODO split lines into values
List
<
Map
<
String
,
String
>>
parsedLines
=
[]
lines
.
each
{
line
->
Map
<
String
,
String
>
lineMap
=
[:]
def
values
=
splitLine
(
line
)
headers
.
eachWithIndex
{
header
,
index
->
lineMap
[
header
]
=
values
[
index
]
}
parsedLines
<<
lineMap
}
println
parsedLines
.
dump
()
println
parsedLines
writer.groovy
0 → 100755
View file @
84625e20
#
!
/usr/
bin
/
env
groovy
String
escape
(
String
unescaped
)
{
if
(!
unescaped
)
{
return
'""'
}
return
'"'
+
unescaped
.
replaceAll
(~
/"/
,
'""'
)
+
'"'
}
assert
escape
(
'asdf'
)
==
'"asdf"'
assert
escape
(
'as"df'
)
==
'"as""df"'
assert
escape
(
null
)
==
'""'
def
writeToCsv
(
List
<
Map
<
String
,
String
>>
inputMap
)
{
// print headers
Set
<
String
>
headers
=
[]
inputMap
.
each
{
it
.
each
{
k
,
v
->
headers
.
add
(
k
)
}
}
println
headers
.
collect
{
escape
(
it
)
}.
join
(
","
)
// print values as CSV
inputMap
.
each
{
Map
<
String
,
String
>
lineMap
->
println
headers
.
collect
{
String
key
->
escape
(
lineMap
[
key
])
}.
join
(
','
)
}
}
List
<
Map
<
String
,
String
>>
inputMap
=
[
[
name:
'Andrey'
,
email:
'andrey@cc.de'
],
[
name:
'Sems'
,
email:
'sems@cc.de'
,
company:
'cc'
]
]
writeToCsv
(
inputMap
)
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment