Created
October 4, 2018 04:34
-
-
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.
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
// 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