Skip to content

Instantly share code, notes, and snippets.

@Zellius
Created February 24, 2019 19:41
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 Zellius/ef752727c8273a5f3df1402662a5af7f to your computer and use it in GitHub Desktop.
Save Zellius/ef752727c8273a5f3df1402662a5af7f to your computer and use it in GitHub Desktop.
Headings into structured Node test
data class Heading(val weight: Int, val text: String)
data class Node(val heading: Heading, val children: MutableList<Node>)
/**
* Convert [headings] into structured [Node]
*
* @throws IllegalArgumentException if [headings] does not have any items
*/
fun headingsIntoStructure(headings: Iterator<Heading>): Node {
if (!headings.hasNext()){
throw IllegalArgumentException("Iterator cannot be empty")
}
lateinit var rootNode: Node
val stack = Stack<Node>()
headings.forEach { currentHeading ->
val node = currentHeading.intoNode()
if (stack.empty()) {
rootNode = node
stack.push(rootNode)
} else {
while (!stack.empty() && stack.peek().heading.weight >= currentHeading.weight) {
stack.pop()
}
val currentNode = stack.peek()
currentNode.children.add(node)
stack.push(node)
}
}
return rootNode
}
fun Heading.intoNode() = Node(this, arrayListOf())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment