Neat trick: .reduce(Object.assign, {})
Description
https://twitter.com/maxfmckay/status/1396252890721918979?s=20
Hello friends. So today I did some live streaming and you can actually
watch it. It's maybe two and a half hours or so of live streaming and I was
working on my KCD bot and in the process of working on this I came across a
interesting type script situation that led to some pretty interesting
learnings about TypeScript, but one I had a couple of people who were kind
of helping along this is one of the things I love about live streaming and
Rupert who actually I mentioned a couple maybe a week ago.
Well who contributed the gratitude to sub command of the things command had
a just a brilliant idea or just kind of a tip of something that he's kind
of taken for granted because he just does it so much but it was really a
great idea in my mind and that is with using reduced and object at a sign.
So let's say that you've got an array that you want to turn into an object
and so you can do a four of loop which is what I actually do most often but
you can actually also do.Use for that and I've done that quite a bit. But
it's kind of confusing sometimes and so what I often will do is I'll filter
out the things I don't want and then I'll map over things to leave myself
with an array of key value pairs and then I will reduce that into an object
of all the values.
Well, anyway what Rupert did was did the filter and then the map and then
made a reduce where the,Reducer function is just object at a sign It so you
don't pass a lambda function or anything or arrowfunction, whatever you
just pass object dot assign as the first first argument to reduce and then
the second argument is the initial value of that reduce and that will is
just an object.
And it was just really clever. I encouraged him to share a tweet and so
I'll add a tweet I'll link to that tweet here so you can get a better idea
of what that is. But I do something similar sort of to this with filter
boolean where I have an array and I want to filter out all the falsie
values.
So I'll say dot filter and then I'll just pass the Boolean constructor and
that does the same thing. So or well and it filters out falsely values. And
so that was a trick that people are always surprising and kind of like, oh
that's kind of cool. And this was a very similar sort of thing dot reduce
object dot assign empty object and boom.
You can turn an array of key value pairs into an object using reduced just
so simply. It's pretty cool. Just thought I'd share that with you all. Take
care.




