-
Notifications
You must be signed in to change notification settings - Fork 0
/
22_group_by.clj
38 lines (32 loc) · 1.39 KB
/
22_group_by.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
(ns koans.22-group-by
(:require [koan-engine.core :refer :all]))
(defn get-odds-and-evens [coll]
(let [{odds true evens false} (group-by odd? coll)]
[odds evens]))
(meditations
"To categorize a collection by some function, use group-by."
(= {5, ["hello" "world"], 3, ["foo" "bar"]}
(group-by count ["hello" "world" "foo" "bar"]))
"You can simulate filter + remove in one pass"
(= (get-odds-and-evens [1 2 3 4 5])
((juxt filter remove) odd? [1 2 3 4 5])
[[1 3 5] [2 4]])
"You can also group by a primary key"
(= {1, [{:id 1 :name "Bob"} {:id 1 :last-name "Smith"}], 2, [{:id 2 :name "Jennifer"}]}
(group-by :id [{:id 1 :name "Bob"}
{:id 2 :name "Jennifer"}
{:id 1 :last-name "Smith"}]))
"But be careful when you group by a non-required key"
(= {"Bob" [{:name "Bob" :id 1}]
"Jennifer" [{:name "Jennifer" :id 2}]
nil [{:last-name "Smith" :id 1}]}
(group-by :name [{:id 1 :name "Bob"}
{:id 2 :name "Jennifer"}
{:id 1 :last-name "Smith"}]))
"The true power of group-by comes with custom functions"
(= {:naughty-list [{:name "Jimmy" :bad true} {:name "Joe" :bad true}],
:nice-list [{:name "Jane" :bad false}]}
(group-by #(if (:bad %) :naughty-list :nice-list)
[{:name "Jimmy" :bad true}
{:name "Jane" :bad false}
{:name "Joe" :bad true}])))