Adventures in Readability
Adam La Rosa
Posted on May 17, 2020
Take for example, this block of code that takes info from a COVID api & organizes it.
processData = (results) => {
let states = {};
for (const result in results){
const info = results[result];
const state = info.Province
const city = info.City
if (Object.keys(states).includes(state)) {
if (Object.keys(states[state]).includes(city)) {
states[state][city].push({
date: info.Date,
cases: info.Cases
})
} else {
states[state][city] = []
states[state][city].push({
date: info.Date,
cases: info.Cases
})
}
} else {
states[state] = {}
states[state][city] = []
states[state][city].push({
date: info.Date,
cases: info.Cases
})
}
}
return states;
}
The results are given to this function and sorted into a new object, organized by State and City. During iteration we check to see if the new object being created already has certain keys. Adding to those keys if they exist and creating them if not. But how does this look? Readability-wise I'd say it leaves something to be desired. By separating some concerns we can make this a little easier to look at.
provinceInStates = (entry) => {
const { states } = this.state
return Object.keys(states).includes(entry.Province)
}
countyInState = (entry) => {
const { states } = this.state
return Object.keys(states[entry["Province"]]).includes(entry.City)
}
addEntryToState = (entry) => {
const { Province, City } = entry;
let newStates = this.state.states
newStates[Province][City].push(entry)
}
createEntryInState = (entry) => {
const { Province, City } = entry
let newStates = this.state.states
newStates[Province] = {}
newStates[Province][City] = []
newStates[Province][City].push(entry);
this.setState({ states: newStates })
}
createCountyInState = (entry) => {
const { Province, City } = entry;
let newStates = this.state.states;
newStates[Province][City] = []
newStates[Province][City].push(entry)
this.setState({ states: newStates })
}
sortDataToStates = (data) => {
const {
provinceInStates, countyInState, addEntryToState,
createCountyInState, createEntryInState
} = this;
for (const info in data) {
const entry = data[info];
if (provinceInStates(entry)) {
countyInState(entry) ?
addEntryToState(entry)
:
createCountyInState(entry);
} else {
createEntryInState(entry);
}
}
}
This last function, sortDataToStates, looks a bit easier to read. The logic to determine if the appropriate keys have been added to the final result have been separated out. This in turn has made reading the if condition that much smoother.
Posted on May 17, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.