Skip to content

Commit

Permalink
Add ObservableAstIterator#collectAll shorthand
Browse files Browse the repository at this point in the history
  • Loading branch information
iamgio committed Aug 24, 2024
1 parent e448f7a commit 3990a25
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class ObservableAstIterator : AstIterator {
/**
* Registers a hook that will be called when a node of type [T] is visited.
* @param hook action to be called, with the visited node as parameter
* @param T desired node type
* @return this for concatenation
*/
inline fun <reified T : Node> on(noinline hook: (T) -> Unit): ObservableAstIterator =
Expand All @@ -39,6 +40,16 @@ class ObservableAstIterator : AstIterator {
onFinishedHooks.add(hook)
}

/**
* Collects all the visited nodes of type [T] into a collection.
* @param T node type
* @return an ordered list (DFS order) containing all the visited nodes of type [T] in the tree
*/
inline fun <reified T : Node> collectAll(): List<T> =
mutableListOf<T>().apply {
on<T>(::add)
}

/**
* Attaches a hook to this iterator.
* @param hook hook to attach
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@ import eu.iamgio.quarkdown.context.toc.TableOfContents
*/
class TableOfContentsGeneratorHook(private val context: MutableContext) : AstIteratorHook {
override fun attach(iterator: ObservableAstIterator) {
val headings = mutableListOf<Heading>()

// Collecting headings.
iterator.on<Heading> { headings += it }
val headings = iterator.collectAll<Heading>()

// Generation.
iterator.onFinished {
Expand Down

0 comments on commit 3990a25

Please sign in to comment.