Skip to content

Instantly share code, notes, and snippets.

@Yord
Last active September 18, 2018 22:02
Show Gist options
  • Save Yord/c7721c77920879e8dcf04c74c3726fef to your computer and use it in GitHub Desktop.
Save Yord/c7721c77920879e8dcf04c74c3726fef to your computer and use it in GitHub Desktop.
A javascript template literal transforming a csv to a list of json objects.
// Ramda 0.25.0
import { defaultTo, eqBy, chain, flatten, head, ifElse, join, length, map, of, pipe, split, tail, transpose, trim, zipObj } from 'ramda'
const interleave = pipe(transpose, flatten)
const trimmedValues = separator => pipe(split(separator), map(trim))
const csv = separator => (strings, ...expressions) => {
const lines = pipe(
interleave,
join(''),
split('\n'),
map(trimmedValues(separator))
)([strings, expressions])
const keys = defaultTo([], head(lines))
const rest = tail(lines)
return chain(
ifElse(eqBy(length, keys), pipe(zipObj(keys), of), () => []),
rest
)
}
// Sample usage
const c = csv(',')
const age = 'age'
const paul = 'Paul'
const maryAge = '31'
console.log(
c`name,${age}
${paul},23
Mary,${maryAge}`
)
// [ { name: 'Paul', age: '23' }, { name: 'Mary', age: '31' } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment