Skip to content

Instantly share code, notes, and snippets.

@tarqd
Last active December 31, 2015 02:09
Show Gist options
  • Save tarqd/7919179 to your computer and use it in GitHub Desktop.
Save tarqd/7919179 to your computer and use it in GitHub Desktop.
Quick and dirty interpolation method (outermost pairs only)
// Example Usage
var str = "Result: {foo({bar: true})} other stuff"
var result = interpolate(str,'{', '}', handle_chunk)
console.log(result.join('')) // outputs: Result: success! other stuff
function handle_chunk(chunk) {
var fn = new Function('foo', 'return ' + chunk)
return fn(foo)
}
function foo(data) {
if (data.bar === true) return "success! "
else return "failed :("
}
function interpolate(str, begin_token, end_token, callback) {
// should probably sanitize this input, javascript needs a RegExp.escape method :/
var regexp = new RegExp(begin_token +'|' + end_token, "gm")
, token
, open = 0
, begin = 0
, chunks = []
console.log('str: ', str)
while((token = regexp.exec(str))) {
if (token[0] === begin_token) {
// if we're opening a new interpolated chunk, flush all the previous text to the chunks array
if (open === 0) {
chunks.push(str.substr(begin, token.index - begin))
console.log('text chunk: ', JSON.stringify(chunks[chunks.length - 1]))
begin = token.index + 1
}
open += 1
} else if (token[0] === end_token && open > 0) { // only handle closing outermost pairs
open -= 1
// if we've found the end of an interpolated chunk send it to the callback
if (open === 0) {
chunks.push(callback(str.substr(begin, token.index - begin), begin, token.index - begin))
console.log('interpolated chunk: ', JSON.stringify(chunks[chunks.length - 1]))
begin = token.index + 1
}
}
}
chunks.push(str.substr(begin))
return chunks
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment