The One Thing That Made Me Choose Clojure Over Javascript — How Simplicity Wins
Apr 30, 2022
I’m translating some Clojure
code to Javascript
for my job for transparency for the UI team and I realized why I prefer Clojure for Javascript. Here's the problem:
Select only unique objects from a list
Javascript:
const myDistinctArray = [
...new Set(myObjArray.map(JSON.stringify)),
].map(JSON.parse);
or
// This one presumes unique "id" === unique object
let uniqueObjArray = [
...new Map(
objArray.map((item) => [item["id"], item])
).values(),
];
Clojure
(distinct my-object-list) // that's it
Why does the Clojure one work?
Clojure promotes immutability by default, and this includes maps. So maps are compared directly by value and not by reference or identity.
Conclusion
The beautiful thing about Clojure is how expressive the language is and how much you can say with very few lines of code.
Read this post and more on my Typeshare Social Blog