Last active
September 18, 2018 22:02
-
-
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.
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
// 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