25
loading...
This website collects cookies to deliver better user experience
enum
to define the suits:enum Suit {
Clubs = '♣️',
Spades = '♠️',
Diamonds = '♦️',
Hearts = '♥️',
}
enum
value. In our case we could split a deck of cards into clubs, spades, diamods and hearts correspondently.interface Card {
name: string;
suit: Suit;
}
const deck: Card[] = [
{
name: 'Ace',
suit: Suit.Clubs
},
{
name: 'Ace',
suit: Suit.Diamonds
},
{
name: 'Ace',
suit: Suit.Hearts
},
{
name: 'Ace',
suit: Suit.Spades
}
];
{
'♣️': Card[],
'♠️': Card[],
'♦️': Card[],
'♥️': Card[],
}
enum
values as keys and each will hold corresponding array with cards of its type.enum
and a value type and produce a type for the object, which would have its properties based on enum values. Let's make it as abstract as possible:type GroupedValues<T extends PropertyKey, V> = {
[K in T]: V
}
function groupItemsBy<T, P extends PropertyKey>(items: T[], groupingKey: keyof T, enu: Record<string, string>): GroupedValues<P, T[]>
enum
. As arguments we will pass the collection, the name of the field, by which we are going to do the grouping, and the enum
itself, which is basically a Record<string, string>
type object.enum
values, use them to make an empty object with arrays to store items from our collection, and then to iterate our collection pushing each item to the corresponging array which has the same name as the passed property value:function groupItemsBy<T, P extends PropertyKey>(items: T[], groupingKey: keyof T, enu: Record<string, string>): GroupedValues<P, T[]> {
const result: GroupedValues<P, T[]> = Object.values(enu).reduce((a: GroupedValues<P, T[]>, b) => {
a[b as P] = [];
return a;
}, {} as GroupedValues<P, T[]>);
items.forEach(i => {
const key = i[groupingKey] as unknown as P;
result[key].push(i);
});
return result;
}
const { "♣️": clubs, "♦️": diamonds, "♥️": hearts, "♠️": spades } = groupItemsByProperty<Card, Suit>(deck, 'suit', Suit);