redplanetlabs / specter

Clojure(Script)'s missing piece
Apache License 2.0
2.51k stars 102 forks source link

Getting current depth while navigating through a tree-like structure #319

Closed robhanlon22 closed 2 years ago

robhanlon22 commented 2 years ago

Let's say I have a tree structure like this:

{:value 1 :children [{:value 2 :children []} {:value 3 :children [{:value 4 :children []}]}}]

Now, let's say I want to do something only on nodes with a depth of 1, i.e. the nodes with values 2 and 3. Is this possible using collect, a recursive, or walker? Or is there just something I'm not thinking of? Thanks in advance :)

nathanmarz commented 2 years ago

If all you care about is nodes at depth 1, then you can just use the path [:children ALL]. For other depth values, you could dynamically construct a path targeting only that depth using comp-navs to compose multiple (path :children ALL) together. Otherwise, the generic technique for keeping track of your depth in a recursive path is to use value collection and then to check the number of collected values with collected?.