Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Created October 4, 2018 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/dd51078a5a3003d0191a76413a6d70f7 to your computer and use it in GitHub Desktop.
Save ccnokes/dd51078a5a3003d0191a76413a6d70f7 to your computer and use it in GitHub Desktop.
Parse basic bash brace expansions. Demo: https://jsfiddle.net/ccnokes/kdqm5o7f/. Just because. I should learn how to write a compiler/interpreter thing for real.
// Test it...
console.log(
expandBraces('test-{a,b,c}-test')
);
/* test-a-test test-b-test test-c-test */
function expandBraces(str) {
let { preamble, expressionList, postscript } = parse(str);
return expressionList
.map(str => `${preamble}${str}${postscript}`)
.join(' ')
}
function parse(str) {
let openingBrace = str.match(/{/);
let closingBrace = str.match(/}/);
if (!openingBrace || !closingBrace) {
throw new Error('Must pass an opening/closing brace');
}
let preamble = str.slice(0, openingBrace.index);
let postscript = str.slice(closingBrace.index + 1, str.length);
let expressionRaw = str.slice(openingBrace.index + 1, closingBrace.index);
let expressionList = expressionRaw.split(',');
if (expressionList.length === 0) {
throw new Error('Must pass at least one item in the expression list');
}
return { preamble, expressionList, postscript };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment