I'm calling an API where the response reduces repetition with a relational data structure where one set of data refers to a second set. Here is an example of the structure:
{
products: [
{
name: 'Wine',
restrictions: ['age'],
},
{
name: 'Pain killers',
restrictions: ['bulk-limit'],
},
{
name: 'Chocolate',
restrictions: [],
},
],
restrictions: [
{
type: 'age',
minAge: 18,
},
{
type: 'bulk-limit',
maxQuantity: 2,
},
],
}
The consumer needs to thread this data together by using the products
that each contain a restrictions
array of string
s which relate to the data in the restrictions
array. My first question is, does this data structure have a common name?
Secondly, I've written a function to thread the data together into a single array of products:
function mapRestrictionsToProducts(response: ProductsResponse): Product[] {
let restrictionMap = new Map<string, Restriction>();
response.restrictions.forEach((restriction) => {
switch (restriction.type) {
case 'age':
return restrictionMap.set('age', {
type: 'age',
minAge: restriction.minAge,
});
case 'bulk-limit':
return restrictionMap.set('bulk-limit', {
type: 'BULK_BUY_LIMIT',
maxQuantity: restriction.maxQuantity,
});
default:
console.warn('Unknown restriction', restriction);
return;
}
});
return response.products.map(p => {
let product: Product = {
name: p.name,
restrictions: p.restrictions.reduce<Restriction[]>(
(prev, curr) => {
let mappedRestriction = restrictionMap.get(curr);
if (mappedRestriction) {
prev.push(mappedRestriction);
}
return prev;
},
[]
),
};
return product;
});
}
Even though this function does what is needed, it does contain two array maps, one of which contains a reduce, and it feels overly complex. Are there any better options with which to iterate over this data and produce the same result?