Currently, I am in the process of restructuring two getters within vuex. Within my state, there exists a predefined array of objects like so:
state: {
color: 'All colors',
size: 'All sizes',
allShoes: [
{
productId: 1,
productno: 1234,
type: 'sneakers',
brand: 'Nike',
model: 'Air Zoom',
gender: 'Men',
size: ['39', '40', '41', '42', '43', '44', '45'],
price: 120,
color: 'red',
outerMaterial: 'Textile',
lining: 'Textile',
sole: 'Textile',
casingThickness: 'Thin lining',
fabric: 'Knitwear',
colors: ['red', 'blue', 'green'],
image: require('@/assets/images/nike-air-zoom.jpg'),
},
{
productId: 2,
productno: 1235,
type: 'sneakers',
brand: 'Adidas',
model: 'Ultra Boost',
gender: 'Men',
size: ['41', '42', '43', '44', '45'],
price: 130,
color: 'white',
outerMaterial: 'Textile',
lining: 'Textile',
sole: 'Textile',
casingThickness: 'Thin lining',
fabric: 'Knitwear',
colors: ['red', 'blue', 'orange'],
image: require('@/assets/images/adidas-ultra.jpg'),
},
For the full application, click here.
The intention is to filter products based on color and size. The current solution involves these two getters:
getters: {
getProductById: (state) => (id) => {
return state.allShoes.find((shoe) => shoe.productId === id);
},
getProductsByGender: (state) => (gender) => {
if (state.color === 'All colors' && state.size === 'All sizes') {
return state.allShoes.filter((shoe) => shoe.gender === gender);
} else {
return state.allShoes.filter((shoe) => {
return (
(state.color === 'All colors' ||
(shoe.color === state.color && shoe.gender === gender)) &&
(state.size === 'All sizes' || shoe.size.includes(state.size)) &&
shoe.gender === gender
);
});
}
},
getProductsByType: (state) => (type) => {
if (state.color === 'All colors' && state.size === 'All sizes') {
return state.allShoes.filter((shoe) => shoe.type === type);
} else {
return state.allShoes.filter((shoe) => {
return (
(state.color === 'All colors' ||
(shoe.color === state.color && shoe.type === type)) &&
(state.size === 'All sizes' || shoe.size.includes(state.size)) &&
shoe.type === type
);
});
}
},
}
It has become apparent that there is duplication in code between getProductsByGender and getProductsByType, leading me to consider consolidating them into one getter. In getProductsByGender, filtering by array method is used where access to shoe.gender is required. Comparatively, getProductsByType demands access to shoe.type. Any suggestions for refactoring these two getters or perhaps utilizing a mixin for cleaner implementation would be greatly appreciated as it seems like I may not be following the DRY principle effectively. Your input is valued.