Skip to content

Instantly share code, notes, and snippets.

@pmuellr
Last active August 29, 2015 14:13
Show Gist options
  • Save pmuellr/745fc75d280568cd22e3 to your computer and use it in GitHub Desktop.
Save pmuellr/745fc75d280568cd22e3 to your computer and use it in GitHub Desktop.
es6 template string function to expand CoffeeScript object notation to JS objects - run with io.js
var coffee = require("coffee-script")
var x = cson`
a: 1
b: 2
`
console.log(x)
// prints: { a: 1, b: 2 }
console.log(cson`
a: ${x.b}
b: ${x.a}
`)
// prints: { a: 2, b: 1 }
console.log(cson`[
1
2
]`)
// prints: [ 1, 2 ]
console.log(cson`
a: 1
b:
c:
d: 4
`)
// prints: { a: 1, b: { c: { d: 4 } } }
console.log(cson`
x: ${JSON.stringify(x)}
`)
// prints: { x: { a: 1, b: 2 } }
//------------------------------------------------------------------------------
function cson(lits) {
var subs = [].slice.call(arguments, 1)
var source = []
for (var i=0; i<subs.length; i++) {
source.push(lits[i])
source.push(subs[i])
}
source.push(lits[lits.length-1])
var result
var source = source.join("")
var ePrefix = `error compiling '${JSON.stringify(source)}'`
try {
result = coffee.compile(source, {bare: true})
}
catch (e) {
throw new Error(`${ePrefix}: error compiling CoffeeScript: '${JSON.stringify(source)}': ${e.message}`)
}
try {
result = eval(result)
}
catch (e) {
throw new Error(`${ePrefix}: error evaluating: '${JSON.stringify(result)}': ${e.message}`)
}
return result
}
@pmuellr
Copy link
Author

pmuellr commented Jan 16, 2015

This is more of an experiment to see what "simpler" JSON object literals might look like. CoffeeScript and eval are overkill, but easy to play with. I should try using my sloppy json parser instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment