August 23, 2018
Just Juxt #9: Split by type (4clojure #50)
Write a function which takes a sequence consisting of items with different types and splits them up into a set of homogeneous sub-sequences. The internal order of each sub-sequence should be maintained, but the sub-sequences themselves can be returned in any order (this is why 'set' is used in the test cases).
Here's an interactive testing area if you want to try solving it:
(ns live.test
(:require [cljs.test :refer-macros [deftest is testing run-tests]]))
(defn split-by-type [s]
)
(deftest split-by-type-test
(is (= (set (split-by-type [1 :a 2 :b 3 :c])) #{[1 2 3] [:a :b :c]}))
(is (= (set (split-by-type [:a "foo" "bar" :b])) #{[:a :b] ["foo" "bar"]}))
(is (= (set (split-by-type [[1 2] :a [3 4] 5 6 :b])) #{[[1 2] [3 4]] [:a :b] [5 6]})))
(run-tests)
Here's a common way:
(defn split-by-type [s]
(vals (group-by type s)))
(run-tests)
And here it is with juxt
:
(defn split-by-type [s]
((comp vals (partial group-by (juxt keyword? vector?))) s))
(run-tests)