Skip to content

Instantly share code, notes, and snippets.

@UpperCod
Created October 4, 2020 21:06
Show Gist options
  • Save UpperCod/346a959bb4ad379360797e8770f4c396 to your computer and use it in GitHub Desktop.
Save UpperCod/346a959bb4ad379360797e8770f4c396 to your computer and use it in GitHub Desktop.
const add = (list) => (rule) => list.push(rule) && "";
const cssBlock = /([^}{;]*){([^}{]+)}/;
function parse(css) {
let blocks = [];
let current;
while(current = css.match(cssBlock)){
const [fragment,selector,content] = current;
const [spaces] = selector.match(/^ */);
const { index: start } = current;
const { length } = fragment;
const end = fragment.length+start;
const children = [];
const block = {selector:selector.trim(),content:content.trim(),start:start+spaces.length,end,children};
blocks = blocks.reduce((blocks,b)=>{
(block.start < b.start && b.end < block.end ? children : blocks).push(b);
return blocks;
},[])
block.children = children;
blocks.push(block)
css = css.slice(0,start)+" ".repeat(length)+css.slice(end);
}
return blocks;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment