-
-
Save marthakelly/3025298 to your computer and use it in GitHub Desktop.
Recursing through a nested block data structure (code simplified for discussion)
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
[ | |
{ | |
"indentLevel": 0, | |
"selector": "body", | |
"declarations": [ | |
" margin: auto", | |
" width: 1000px" | |
], | |
"children": [] | |
}, | |
{ | |
"indentLevel": 0, | |
"selector": "#divID", | |
"declarations": [ | |
" font: 12px Helvetica, Arial, sans-serif", | |
" color: green", | |
" background: yellow" | |
], | |
"children": [ | |
{ | |
"indentLevel": 1, | |
"selector": ".className", | |
"declarations": [ | |
" color: blue", | |
" width: 500px" | |
], | |
"children": [] | |
} | |
] | |
} | |
] |
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
var holder = []; | |
var cssFormat = function cssFormat (tree, prefix) { | |
prefix = prefix || ""; | |
return tree.map(function(elem, i){ | |
var beginBlock = " {" + "\n", | |
endBlock = "\n" + "}", | |
sel = prefix + elem.selector, | |
dec = elem.declarations.join("; \n") + ";", | |
block, | |
children = "", | |
parents; | |
block = sel + beginBlock + dec + endBlock; | |
holder.push(JSON.stringify(block, undefined, 2)); | |
if (elem.children.length) { | |
children = cssFormat(elem.children, sel); | |
} | |
return block; | |
}); | |
}; |
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
var blockToCSS = function blockToCSS(block) { | |
var beginBlock = " {" + "\n", | |
endBlock = "\n" + "}", | |
output = [], | |
sel, | |
dec, | |
block, | |
parentCSS; | |
sel = block.selector + " "; | |
dec = block.declarations.join("; \n") + ";"; | |
parentCSS = sel + beginBlock + dec + endBlock; | |
if (!block.children.length) { | |
return [parentCSS]; | |
} else { | |
var childrenCSS = block.children.map(blockToCSS).reduce(function(acc, children) { | |
return acc.concat(children); | |
}); | |
var prefixedChildrenCSS = childrenCSS.map(function(child) { | |
return sel + child; | |
}); | |
prefixedChildrenCSS.unshift([parentCSS]); | |
return prefixedChildrenCSS; | |
} | |
}; | |
var output = formatBlocks(lineObjects).map(blockToCSS); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment