Hi all,
I am practicing filters and sorting data in JS by building a simple Vue app. So far things are going well, but I have some questions as to how to optimize my filter functions and make them more reusable / generic.
LINK TO CURRENT LIVE CODE: https://awesome-lichterman-e60bed.netlify.com/#/city-search
As you can see below, it works fine, but it feels like I’m not being very DRY with my code.
I just have 2 questions:
- Does anyone have any tips/suggestions/links to help me refactor this code.
- And what is the best practice / method for chaining filters ontop of each other
(eg) Filter by letter ‘A’ and then whatever cities start with ‘A’ can then be filtered by Rank, Population etc but without overriding the current filter.
In my Vuex store, I have the following mutation functions, all which filter data but just a little differently for each function.
// state.js
export const state = {
cities: [],
filteredCities: [],
filters: {
byLetter: '',
byPopulationSize: '',
sortByAtoZ: false,
sortByRank: []
},
loadingComplete: false
}
// a typical city item
{
city:"New York"
growth_from_2000_to_2013:"4.8%"
latitude:40.7127837
longitude:-74.0059413
population:"8405837"
rank:"1"
state:"New York"
}
// mutations.js
// TODO: Create Filter Util Function to just call ONE main filter func.
export const mutations = {
SET_FILTER_BY_LETTER (state, payload) {
state.filters.byLetter = payload
const filter = state.cities.filter((city) => {
return city.city[0].toLowerCase() === payload.toLowerCase()
})
state.filteredCities = filter
},
SET_FILTER_BY_POPULATION (state, payload) {
state.filters.byPopulationSize = payload
const filter = state.cities.filter((city) => {
return city.population >= payload
})
state.filteredCities = filter
},
SORT_CITIES_A_TO_Z (state, payload) {
state.filters.sortByAtoZ = payload
return (!payload)
? state.filteredCities.sort((a, b) => b.city.toLowerCase() < a.city.toLowerCase())
: state.filteredCities.sort((a, b) => b.city.toLowerCase() > a.city.toLowerCase())
},
SORT_CITIES_BY_RANK (state, payload) {
state.filters.sortByRank = payload
let [ low, high ] = payload
const filter = state.cities.filter((city) => {
return city.rank >= low && city.rank <= high
})
state.filteredCities = filter
}
}
Thanks in advance