I would recommend looking at how you are structuring your code and how you could begin extracting things that change based on conditions into a container object with property objects which contain the data you want to apply based on a condition.
For example, my weather app can be found here:
I wrote it so that the UI would change color schemes based on time of day and weather conditions (including a special twilight condition to give a sunrise/sunset color scheme).
Rather than hard coding a bunch of if statements with weather codes, I pulled all of that data into a config object, which I could then reference directly.
This is my function for inserting current weather conditions and updating UI CSS classes based on the data:
function ui_insert_current_conditions( $body, conditions ){
const weather_condition = config.weather_conditions[ conditions.weather[ 0 ].id ];
const $container = $body.find( 'div.middle' );
const classes_to_add = [];
const icons = weather_condition.icons;
classes_to_add.push( weather_condition.css_class );
$container
.find( 'h1.location_name' )
.text( conditions.name )
.end()
.find( 'h3.current_conditions' )
.text( weather_condition.condition )
.end()
.find( 'div.weather_icon img.day' )
.attr( 'src', ( icons ) ? icons.day : '' )
.end()
.find( 'div.weather_icon img.night' )
.attr( 'src', ( icons ) ? icons.night : '' )
.end();
ui_insert_temperature( $container.find( 'div.info.temperature' ), conditions, 'F' );
ui_insert_wind( $container.find( 'div.info.wind'), conditions );
ui_insert_location_data( $container.find( 'div.info.latlong' ), conditions.coord );
$container.find( '.info' ).removeClass( 'hidden' );
$body
.removeClass( config.condition_classes )
.addClass( classes_to_add.join( ' ' ) );
}
All weather_condition
objects are structured the same way. This is an example of a weather_condition
object found on the config
object:
{
'200': {
'condition': 'Thunderstorms with light rain.',
'css_class': 'thunderstorm',
'icons' : {
'day' : 'http://www.michealhallphotography.com/mystuff/fcc/weatherapp/images/icons/01.png',
'night' : 'http://www.michealhallphotography.com/mystuff/fcc/weatherapp/images/icons/01.png'
}
}
If you read through the function, you’ll see that it’s updating the interface, but it has absolutely no idea what the current conditions are - and it shouldn’t care what they are. All it is doing is getting a reference to a weather configuration object based on the conditions passed in, and then applying that configuration data to the UI.
That makes it a generic function which can be extended at any time by adding more weather conditions to the config object, with no changes whatsoever to the code itself. No more if
or else
statements. Your ui function is kept very lean and clean.
It’s a very good idea to separate out data from logic. Make the logic as generic as possible. Structure the data consistently. Then functions can become much, much simpler.
~Micheal