diff options
| author | Michael Williamson <mike@zwobble.org> | 2015-10-13 22:10:42 +0100 |
|---|---|---|
| committer | Michael Williamson <mike@zwobble.org> | 2015-10-13 22:10:42 +0100 |
| commit | aac776b1711d1e286812035a28108c622e73994a (patch) | |
| tree | 366673f18143771fabbadb0fcef86d638ce33f43 /lib/html/simplify.js | |
| parent | 2fb7a36230b167aac99fe8d43959833bd3b244dd (diff) | |
Add simplification of nodes
Diffstat (limited to 'lib/html/simplify.js')
| -rw-r--r-- | lib/html/simplify.js | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/lib/html/simplify.js b/lib/html/simplify.js new file mode 100644 index 0000000..52a1b0a --- /dev/null +++ b/lib/html/simplify.js @@ -0,0 +1,44 @@ +var _ = require("underscore"); + +var ast = require("./ast"); + +function simplify(node) { + return simplifiers[node.type](node); +}; + +var simplifiers = { + fragment: simplifyFragment, + element: simplifyElement, + text: simplifyText +}; + +function simplifyFragment(node) { + return ast.fragment(simplifyNodes(node.children)); +} + +function simplifyElement(node) { + return ast.elementWithTag(node.tag, simplifyNodes(node.children)); +} + +function simplifyText(node) { + return node; +} + +function simplifyNodes(nodes) { + var children = []; + + nodes.map(simplify).forEach(function(child) { + var lastChild = children[children.length - 1]; + if (child.type === "element" && !child.tag.fresh && lastChild && _.isEqual(lastChild.tag, child.tag)) { + child.children.forEach(function(grandChild) { + // Mutation is fine since simplifying elements create a copy of the children. + lastChild.children.push(grandChild); + }); + } else { + children.push(child); + } + }); + return children; +} + +module.exports = simplify; |
