(array, keyFunction, collect = false)
| 26 | } |
| 27 | |
| 28 | export function groupBy(array, keyFunction, collect = false) { |
| 29 | if (array.length === 0) return []; |
| 30 | if (keyFunction === undefined) keyFunction = each => each; |
| 31 | const keyToGroup = new Map(); |
| 32 | const groups = []; |
| 33 | const sharedEmptyArray = []; |
| 34 | let id = 0; |
| 35 | // This is performance critical, resorting to for-loop |
| 36 | for (let each of array) { |
| 37 | const key = keyFunction(each); |
| 38 | let group = keyToGroup.get(key); |
| 39 | if (group !== undefined) { |
| 40 | collect ? group.addEntry(each) : group.add(); |
| 41 | continue; |
| 42 | } |
| 43 | let entries = collect ? [each] : sharedEmptyArray; |
| 44 | group = new Group(key, id++, array.length, entries, 1); |
| 45 | groups.push(group); |
| 46 | keyToGroup.set(key, group); |
| 47 | } |
| 48 | // Sort by length |
| 49 | return groups.sort((a, b) => b.length - a.length); |
| 50 | } |
| 51 | |
| 52 | export function arrayEquals(left, right, compareFn) { |
| 53 | if (left == right) return true; |
no test coverage detected