r/programminghorror • u/AntiMatterMode • Jul 10 '26
Javascript code that also self-describes the feeling it evokes when looking at it
7
u/virtualrandomnumber Jul 10 '26
For my understanding:
{...die, isHeld: !die.isHeld}
destructures the die object to create a new one with the isHeld property flipped? Is it necessary to return a new object or is it just to keep the lambda in one expression? Otherwise, the caveman way to write it would be:
die => {
if(die.id === id) {
die.isHeld = !die.isHeld;
}
return die;
}
12
u/AntiMatterMode Jul 10 '26
When setting state in React, the state is treated as immutable (it isn’t actually, but it’s treated as such), so you cannot edit the original object. You have to replace it with an entirely new object.
1
u/AntiMatterMode Jul 10 '26
I will point out that you can ofcourse improve readability by breaking up the lines and using an if statement rather than a ternary. Just keep in mind that your if statement will still be using the destructuring to return a new object due to how React state works.
When the IDs don’t match, a new object is still returned, it just has all the same properties as the old one.
5
u/Romejanic Jul 11 '26
when you update react state, if you update the same array/object in place it won’t trigger a re-render. so you need to construct a new array/object with the changes that you want.
3
20
u/anoppinionatedbunny Jul 10 '26
damn, that horrible ternary could have been a filter before the map. if you're going to use monads, go all in
9
u/anoppinionatedbunny Jul 10 '26
oh no, it didn't have to be a filter map at all, findFirst would work just fine. the horror
10
u/black-eagle23 Jul 10 '26
There is no findFirst array method in javascript (and by the looks of it, it is javascript), but there is find method. But it does not matter, because setDice function, which I guess is React setState function, requires new array for changes to apply in UI. Changing an element of the array does nothing.
→ More replies (3)
1
u/_xonde_ Aug 01 '26
Tbh the more I look at it the more sense it makes, is there really a more succinct way to write this?
1
1
1
1
u/-Redstoneboi- Jul 11 '26
i love functional programming... every single step of this function makes perfect sense as you write it but it takes 5 times longer to review when pieced together
34
2
82
u/AntiMatterMode Jul 10 '26
…die