Created
February 24, 2019 19:41
-
-
Save Zellius/ef752727c8273a5f3df1402662a5af7f to your computer and use it in GitHub Desktop.
Headings into structured Node test
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
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