mirror of
https://gitlab.com/openstapps/openstapps.git
synced 2026-03-15 03:02:11 +00:00
fix: daia availability
This commit is contained in:
committed by
Rainer Killinger
parent
b38a96996a
commit
13cee2d426
@@ -13,7 +13,7 @@
|
||||
* this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {groupBy, groupByProperty} from './group-by';
|
||||
import {groupBy, groupByStable, groupByProperty} from './group-by';
|
||||
|
||||
describe('groupBy', () => {
|
||||
it('should group an array by a key', () => {
|
||||
@@ -77,6 +77,29 @@ describe('groupBy', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('groupByStable', () => {
|
||||
const array = [
|
||||
{id: 2, name: 'two'},
|
||||
{id: 4, name: 'three'},
|
||||
{id: 3, name: 'three'},
|
||||
{id: 1, name: 'one'},
|
||||
];
|
||||
const result = groupByStable(array, it => it.name);
|
||||
|
||||
it('should group an array by keys', () => {
|
||||
expect(result.get('one')).toEqual([{id: 1, name: 'one'}]);
|
||||
expect(result.get('two')).toEqual([{id: 2, name: 'two'}]);
|
||||
expect(result.get('three')).toEqual([
|
||||
{id: 4, name: 'three'},
|
||||
{id: 3, name: 'three'},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should provide ordered keys', () => {
|
||||
expect([...result.keys()]).toEqual(['two', 'three', 'one']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('groupByProperty', function () {
|
||||
it('should group by property', () => {
|
||||
const array = [
|
||||
|
||||
@@ -28,6 +28,21 @@ export function groupBy<T>(
|
||||
}, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Group an array by a function (returns a Map, whose keys keep order info of items entry)
|
||||
*/
|
||||
export function groupByStable<T>(
|
||||
collection: T[],
|
||||
group: (item: T) => string | undefined,
|
||||
): Map<string, T[]> {
|
||||
return collection.reduce((accumulator: Map<string, T[]>, item) => {
|
||||
const key = group(item) ?? '';
|
||||
accumulator.set(key, accumulator.get(key) ?? []);
|
||||
accumulator.get(key)?.push(item);
|
||||
return accumulator;
|
||||
}, new Map<string, T[]>());
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user