3 ms·
Yes, it errors out. And flatMap isn't applicable here. Here's some complete test code you can try in your browser right now: ``` let p = (a,fn) => Object.fromE
by javajosh 7y ago
Yes, it errors out. And flatMap isn't applicable here. Here's some complete test code you can try in your browser right now:
```
let p = (a,fn) => Object.fromEntries(Object.entries(a).map(fn))
p({a:1, b:2}, ([k,v])=> v === 2 ? undefined : [k,v])
```
My intent is to skip the entry with `b:2`. However, both map and flatMap error out. It would be nice if `fromEntries` did what I think is the appropriate thing, which is just skip undefined and null. Is this not the behavior you'd expect?
Note that without special treatment in fromEntries, there's no way for the mapping function to indicate "skip this entry". You have to do it in another pass, or some other way.
- masklinn 7y ago> And flatMap isn't applicable here. It's absolutely applicable, flatMap can trivially act as a filterMap by returning an empty array in the "remove this element" case: let p = (a,fn) => Object.fromEntries(Object.entries(a).flatMap(fn)) p({a:1, b:2}, ([k,v])=> v === 2 ? [] : [[k,v]]) there you go. You can even make the adaptation transparent by wrapping the fn: let p = (a,fn) => Object.fromEntries(Object.entries(a).flatMap((v) => { let r = fn(v); return r == null ? [] : [r]; })); p({a:1, b:2}, ([k,v])=> v === 2 ? undefined : [k,v]) > My intent is to skip the entry with `b:2`. However, both map and flatMap error out. Return an empty list from flatmap to remove the entry and a singleton list containing the new pair to alter it. > Is this not the behavior you'd expect? No. I would much rather have the existing function which has a very clear and straightforward behaviour and is not prone to silently misbehaving on buggy code. > Note that without special treatment in fromEntries, there's no way for the mapping function to indicate "skip this entry". I fail to see an issue with that. If you want to remove an entry, remove the entry.