4 ms·
A «group by» function requires keys to be comparable (for equality). You can see this when you look at the type signatures of «group by» functions in any strong
by wereHamster 5y ago
A «group by» function requires keys to be comparable (for equality). You can see this when you look at the type signatures of «group by» functions in any strongly typed language or library. They either require a comparator to be provided, or infer it from the context (type classes in Haskell). JavaScript has quite intuitive equality for primitive types (strings, symbols), but nothing that would be natural for complex objects.
Consider this array: [{ key: {}, foo: 1 }, { key: {}, foo: 2 }], there are multiple answers how a Map can look when you group by 'key'. Both comparing the keys using '===' and deep equality are valid options, depending on needs.
- yashap 5y agoJS maps already have a well defined way that they do key equality: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#key_equality https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... It's basically just strict equality (===), except NaN === NaN is false, while they're considered equal for map keys. So in your example, you'd have 2 entries, since {} !== {}. It sounds like they're going to implement `groupByToMap` as well as `groupBy`, and I assume `groupByToMap` will just use the normal map key equality rules, and I guess the "first" key matching that equality will be used for the grouping.
- wereHamster 5y agoMy point is that you can't override what equality implementation groupByToMap will use, which makes it much less useful. See for example https://gcanti.github.io/fp-ts/modules/NonEmptyArray.ts.html#group https://gcanti.github.io/fp-ts/modules/NonEmptyArray.ts.html..., where you can supply your own equality function…