2021-05-05 20:44:36 +00:00
|
|
|
/**
|
|
|
|
* Part of [Canivete](http://canivete.leofavre.com/#deepgroupby)
|
|
|
|
*
|
|
|
|
* Groups the contents of an array by one or more iteratees.
|
|
|
|
* Unlike Lodash [`groupBy()`](https://lodash.com/docs/4.17.4#groupBy),
|
|
|
|
* this function can create nested groups, but cannot receive
|
|
|
|
* strings for iteratees.
|
|
|
|
*/
|
|
|
|
|
2022-01-06 12:58:10 +00:00
|
|
|
export const groupBy = (e, ...t) => {
|
2021-05-05 20:44:36 +00:00
|
|
|
let r = e.map((e) => t.map((t) => t(e))),
|
2022-01-06 12:58:10 +00:00
|
|
|
a = {}
|
2021-05-05 20:44:36 +00:00
|
|
|
return (
|
|
|
|
r.forEach((t, r) => {
|
2022-01-06 12:58:10 +00:00
|
|
|
let l = (_simpleAt(a, t) || []).concat([e[r]])
|
|
|
|
_simpleSet(a, t, l)
|
2021-05-05 20:44:36 +00:00
|
|
|
}),
|
|
|
|
a
|
2022-01-06 12:58:10 +00:00
|
|
|
)
|
2021-05-05 20:44:36 +00:00
|
|
|
},
|
2022-01-06 12:58:10 +00:00
|
|
|
_isPlainObject = (e) => null != e && "object" == typeof e && e.constructor == Object,
|
2021-05-05 20:44:36 +00:00
|
|
|
_parsePath = (e) => (Array.isArray(e) ? e : `${e}`.split(".")),
|
|
|
|
_simpleAt = (e, t) =>
|
2022-01-06 12:58:10 +00:00
|
|
|
_parsePath(t).reduce((e, t) => (null != e && e.hasOwnProperty(t) ? e[t] : void 0), e),
|
2021-05-05 20:44:36 +00:00
|
|
|
_simpleSet = (e, t, r) =>
|
|
|
|
_parsePath(t).reduce((e, t, a, l) => {
|
2022-01-06 12:58:10 +00:00
|
|
|
let s = a === l.length - 1
|
2021-05-05 20:44:36 +00:00
|
|
|
return (
|
2022-01-06 12:58:10 +00:00
|
|
|
(e.hasOwnProperty(t) && (s || _isPlainObject(e[t]))) || (e[t] = {}), s ? (e[t] = r) : e[t]
|
|
|
|
)
|
|
|
|
}, e)
|