Skip to content

Instantly share code, notes, and snippets.

@kwijibo
Last active December 3, 2015 18:00
Show Gist options
  • Save kwijibo/ac859f9270a704867af0 to your computer and use it in GitHub Desktop.
Save kwijibo/ac859f9270a704867af0 to your computer and use it in GitHub Desktop.
RDF/JSON -> Turtle serialiser w/ Ramda
var prepend = first => second => first + second
, prefix = (item, i) => `@prefix n${i}: <${item}> . \n`
, mapI = R.addIndex(R.map)
, insertIndex = (ns,uri) => ns.push(uri)-1
, nsEnd = uri => Math.max(uri.lastIndexOf('#'), uri.lastIndexOf('/')) +1
, lookup = ns => uri => { const i = ns.indexOf(uri); return 'n' + (i>-1)? i : insertIndex(ns,uri) }
, change0 = R.over(R.lensIndex(0))
, change1 = R.over(R.lensIndex(1))
, literal = ({value,lang,datatype}) => '"'+ value.replace(/("|\n)/g,'\\$1') + '"'+langTag(lang)+dataType(datatype)
, langTag = lang => lang? '@'+lang : ''
, dataType = dt => dt? '^^'+dt : ''
, uri = ns => u => R.pipe(R.splitEvery(nsEnd(u)), change0(lookup(ns)), R.join(':'))(u)
, typeIs = R.propEq('type')
, obj = ns => R.cond([
[typeIs('literal'), literal]
,[typeIs('uri'), R.pipe(R.prop('value'),uri(ns))]
])
, objectValues = ns => R.pipe(R.map(obj(ns)), R.join(', '))
, propObjects = ns => R.pipe(change0(uri(ns)), change1(objectValues(ns)), R.join(' '))
, props = ns=> R.pipe(R.toPairs, R.map(propObjects(ns)), R.join('\n;\t'))
, subProps = ns => R.pipe(change0(uri(ns)), change1(props(ns)), R.join(' '))
, turtle = (data, ns=[]) => {
const body = R.pipe(R.toPairs, R.map(subProps(ns)), R.join(' .\n') )(data)
return mapI(prefix,ns) + body
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment