Last active
December 21, 2015 03:39
-
-
Save marvinthepa/6243971 to your computer and use it in GitHub Desktop.
Functional Hipsters don't like for loops
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; using clojures included batteries | |
(reduce | |
(partial | |
merge-with (fn [x y] (if (seq? x) (conj x y) [x y]))) | |
[{:en "en1" :de "de"} {:en "en2" :de "de2"}]) | |
;; even easier if we already have vectors as values | |
(reduce | |
(partial merge-with concat) | |
[{:en ["en1"] :de ["de"]} {:en ["en2"] :de ["de2"]}]) | |
;; so lets just make vectors out of the values first | |
(->> | |
[{:en "en1" :de "de"} {:en "en2" :de "de2"}] | |
(map (partial clojure.walk/walk (fn [[x y]] [x [y]]) identity)) | |
(reduce (partial merge-with concat))) | |
;; if you don't want to use merge-with, use update-in | |
(reduce | |
(fn [target source] | |
(reduce | |
(fn [agg [key val]] | |
(update-in agg [key] | |
(fn [old new] | |
(if old | |
(conj old new) | |
[new])) | |
val)) | |
target | |
source)) | |
{} | |
[{:en "en1" :de "de"} {:en "en2" :de "de2"}]) | |
;; which is a little bit of overkill in our case, so we can do with just basic FP: | |
(reduce | |
(fn [target source] | |
(reduce | |
(fn [agg [key val]] | |
(assoc agg key | |
(conj (agg key []) val))) | |
target | |
source)) | |
{} | |
[{:en "en1" :de "de"} {:en "en2" :de "de2"}]) | |
;;=> {:de ["de" "de2"], :en ["en1" "en2"]} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// unfortunately, javascript does not look as nice as clojure | |
// and requires some mutation | |
_([{ en: 'en1', de: 'de' }, { en: 'en2', de: 'de2' }]) | |
.reduce(function (target, source) { | |
return _.reduce( | |
source, | |
function(agg, val, key) { | |
var c = _.clone(agg); | |
c[key] = (agg[key] || []).concat([val]); | |
return c; | |
}, | |
target | |
); | |
}, | |
{}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment