Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tree-leafs function #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/potpuri/core.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -412,3 +412,18 @@
(let [g (group-by parent-fn items)]
;; Start with items which have no parent => root items
(build-tree' opts g (get g nil))))

(defn tree-leafs
"Given a tree, branch? predicate and child-fn returns list of found
tree leafs.

If only single function is provided, it is used as both branch? predicate and child-fn."
{:added "0.5.2"}
([tree child-fn]
(tree-leafs tree child-fn child-fn))
([tree branch? child-fn]
(mapcat (fn [node]
(if (branch? node)
(tree-leafs (child-fn node) branch? child-fn)
[node]))
tree)))
12 changes: 11 additions & 1 deletion test/potpuri/benchmark.clj
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
(ns potpuri.benchmark
(:require [potpuri.core :as p]
[criterium.core :as criterium]))
[criterium.core :refer [quick-bench]]))

(comment
(quick-bench (into [1] [2 3 4]))
(quick-bench (apply vector 1 [ 2 3 4])))


(comment
(def tree [{:id "top"
:lapset [{:id "c1"
:lapset [{:id "c11" :lapset [{:id "c12"}]}
{:id "c13"}]}
{:id "c2"}]}])

(quick-bench (p/leafs tree :lapset)))
21 changes: 21 additions & 0 deletions test/potpuri/core_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,24 @@
{:id 3 :parents [1 2]}
{:id 4 :parents [1 2]}])))))
)

(deftest tree-leafs-test
(is (= [{:id 2} {:id 3} {:id 4}]
(p/tree-leafs [{:id 1
:children [{:id 2}
{:id 3}]}
{:id 4}]
:children)))

(testing "branch with empty children list"
(is (= [{:id 1 :children nil}]
(p/tree-leafs [{:id 1
:children nil}]
:children)))

(is (= []
(p/tree-leafs [{:id 1
:children nil}]
#(contains? % :children)
:children))
"Separate branch predicate")))