|
| 1 | +/* |
| 2 | + * Licensed to Elasticsearch B.V. under one or more contributor |
| 3 | + * license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright |
| 5 | + * ownership. Elasticsearch B.V. licenses this file to you under |
| 6 | + * the Apache License, Version 2.0 (the "License"); you may |
| 7 | + * not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +import { each, isFunction } from 'lodash'; |
| 21 | + |
| 22 | +/** |
| 23 | + * Like _.groupBy, but allows specifying multiple groups for a |
| 24 | + * single object. |
| 25 | + * |
| 26 | + * organizeBy([{ a: [1, 2, 3] }, { b: true, a: [1, 4] }], 'a') |
| 27 | + * // Object {1: Array[2], 2: Array[1], 3: Array[1], 4: Array[1]} |
| 28 | + * |
| 29 | + * _.groupBy([{ a: [1, 2, 3] }, { b: true, a: [1, 4] }], 'a') |
| 30 | + * // Object {'1,2,3': Array[1], '1,4': Array[1]} |
| 31 | + * |
| 32 | + * @param {array} collection - the list of values to organize |
| 33 | + * @param {Function} callback - either a property name, or a callback. |
| 34 | + * @return {object} |
| 35 | + */ |
| 36 | +export function organizeBy(collection: object[], callback: ((obj: object) => string) | string) { |
| 37 | + const buckets: { [key: string]: object[] } = {}; |
| 38 | + |
| 39 | + function add(key: string, obj: object) { |
| 40 | + if (!buckets[key]) { |
| 41 | + buckets[key] = []; |
| 42 | + } |
| 43 | + buckets[key].push(obj); |
| 44 | + } |
| 45 | + |
| 46 | + each(collection, (obj: Record<string, any>) => { |
| 47 | + const keys = isFunction(callback) ? callback(obj) : obj[callback]; |
| 48 | + |
| 49 | + if (!Array.isArray(keys)) { |
| 50 | + add(keys, obj); |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + let length = keys.length; |
| 55 | + while (length-- > 0) { |
| 56 | + add(keys[length], obj); |
| 57 | + } |
| 58 | + }); |
| 59 | + |
| 60 | + return buckets; |
| 61 | +} |
0 commit comments