Skip to content

Instantly share code, notes, and snippets.

@jsloat
Last active November 15, 2018 14:49
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 jsloat/917eeb1d43db9415e2b64b9721859147 to your computer and use it in GitHub Desktop.
Save jsloat/917eeb1d43db9415e2b64b9721859147 to your computer and use it in GitHub Desktop.
Usage is a bit rough -- currently I copy and paste the code into a node terminal, then call refactor with a multi-line string as argument (using backticks)
refactor = oldCode => {
const defineBlock = /define\((?:['"].*?['"],\s*)?\[(.*?)\],\s*?(?:function|)\s*?\((.*?)\)/gms;
const match = defineBlock.exec(oldCode);
if (!match) {
return 'No matches found, error';
}
const groupBrackets = (acc, item) => {
const hasBracket = {
left: Boolean(/\{/.exec(item)),
right: Boolean(/\}/.exec(item))
};
const newParsing = acc.parsing && hasBracket.right
? false
: !acc.parsing && hasBracket.left && !hasBracket.right
? true : acc.parsing;
let newData;
item = item.replace(/[\{\}]/g, '');
if (!acc.parsing && !hasBracket.left) {
newData = [...acc.data, item];
} else if (!acc.parsing && hasBracket.left) {
newData = [...acc.data, [item]];
} else if (acc.parsing) {
newData = [
...acc.data.slice(0,acc.data.length-1),
acc.data.slice(-1)[0].concat([item])
];
}
console.log({data: newData, parsing: newParsing});
return {data: newData, parsing: newParsing};
};
const clean = (string, delimiter) =>
string.split(delimiter).map(i => i.trim()).filter(Boolean).join('');
const listify = matchString => matchString
.split(',')
.reduce(groupBrackets, {data: [], parsing: false}).data
.map(item => {
if (!Array.isArray(item)) {
return clean(item, '\n');
}
const listItem = item
.reduce((acc, subitem) => acc.concat(clean(subitem, '\n')), [])
.join(', ');
return `{ ${listItem} }`;
})
.filter(Boolean)
.map(string => string.trim().replace(/,$/gm, ''));
const paths = listify(match[1]);
const modules = listify(match[2]);
if (paths.length !== modules.length) {
console.log('WARNING: Paths and modules mismatched, possible error');
}
paths.forEach((path, index) => {
const module = modules[index];
const result = !module
? `import ${path};`
: `import ${module} from ${path};`
console.log(result);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment