Skip to content

Instantly share code, notes, and snippets.

@marvinthepa
Last active December 21, 2015 03:39
Show Gist options
  • Save marvinthepa/6243971 to your computer and use it in GitHub Desktop.
Save marvinthepa/6243971 to your computer and use it in GitHub Desktop.
Functional Hipsters don't like for loops
;; 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"]}
// 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