Created
April 4, 2019 03:40
-
-
Save madureira/f6d0df659044a5e6f879466911f696d9 to your computer and use it in GitHub Desktop.
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
const Heading = function(weight, text) { | |
this.weight = weight; | |
this.text = text | |
}; | |
const Node = function(heading, children) { | |
this.heading = heading; | |
this.children = children; | |
}; | |
/** | |
* Builds the whole node structure given a heading list. | |
* | |
* @param {array} headings - The headings list. | |
* @param {Node} parentNode - The current node. | |
* @param {int} idx - The headings index. | |
* @param {int} currentWeight - The current weight to compare | |
* | |
* @return {Node} - A Node with nested children. | |
*/ | |
function buildNodeStructure(headings, parentNode, idx, currentWeight) { | |
for (let i = idx; i < headings.length; i++) { | |
const headingWeight = headings[i].weight; | |
if (headingWeight === currentWeight + 1) { | |
const childNode = new Node(headings[i], []); | |
parentNode.children.push(childNode); | |
buildNodeStructure(headings, childNode, i + 1, childNode.heading.weight); | |
} | |
if (headingWeight === currentWeight || headingWeight === currentWeight - 1) { | |
return; | |
} | |
} | |
return parentNode; | |
} | |
/** | |
* Converts a list of input headings into nested nodes | |
* | |
* @param headings: Array of Headings as ordered in the input | |
*/ | |
function toOutline(headings) { | |
// Implement this function. Sample code below builds | |
// an outline of only the first heading | |
return buildNodeStructure(headings, new Node(new Heading(0, ''), []), 0, 0); | |
} | |
// Parses a line of the input | |
// This implementation is correct for all predefined test cases | |
function parse(record) { | |
const firstSpace = record.indexOf(" "); | |
const weight = parseInt(record.substr(1, firstSpace)); | |
const text = record.substr(firstSpace + 1); | |
return new Heading(weight, text); | |
} | |
// Converts a node to HTML | |
function toHtml(node) { | |
let childHtml = ""; | |
if (node.children.length > 0) { | |
childHtml = `<ol>${node.children.map(child => `<li>${toHtml(child)}</li>`).join("\n")}</ol>`; | |
} | |
const heading = node.heading.text.length === 0 ? "" : node.heading.text + "\n"; | |
return heading + childHtml; | |
} | |
process.stdin.resume(); | |
process.stdin.setEncoding("ascii"); | |
var _input = ""; | |
process.stdin.on("data", function (input) { | |
_input += input; | |
}); | |
process.stdin.on("end", function () { | |
const headings = _input.split("\n").map(r => parse(r)); | |
const outline = toOutline(headings); | |
console.log(toHtml(outline)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment