Skip to content

Instantly share code, notes, and snippets.

@mike-pete
Last active October 26, 2024 17:52
Show Gist options
  • Save mike-pete/64e968b7db4bc48ceb4f7bd65d905888 to your computer and use it in GitHub Desktop.
Save mike-pete/64e968b7db4bc48ceb4f7bd65d905888 to your computer and use it in GitHub Desktop.
Initialize conditionally with anon function

So let's say I'm building a website to tell me what I should wear based on the current weather (raining, sunny, snowing).

I only use the app once per day, and the weather won't change while I'm looking at the app, so the clothing choice should be constant.

I also want the code to be easy to read so other members of my team can easily understand the code.

enum Weather {
RAINING,
SUNNY,
SNOWING
}
enum Clothing {
RAIN_COAT,
SHIRT,
COAT,
}
const weather: Weather = Weather.RAINING as Weather;
let shouldWear: Clothing
switch (weather) {
case Weather.RAINING:
shouldWear = Clothing.RAIN_COAT;
break;
case Weather.SUNNY:
shouldWear = Clothing.SHIRT;
break;
case Weather.SNOWING:
shouldWear = Clothing.COAT;
break;
}
// This is easy to read and understand, but it's not using a const,
// so we lose the write protections and the implication that this won't change.
enum Weather {
RAINING,
SUNNY,
SNOWING
}
enum Clothing {
RAIN_COAT,
SHIRT,
COAT,
}
const weather: Weather = Weather.RAINING as Weather;
const shouldWear: Clothing =
weather === Weather.RAINING
? Clothing.RAIN_COAT
: weather === Weather.SNOWING
? Clothing.COAT
: Clothing.SHIRT;
// This is constant, but nested ternaries are hard to read and understand.
enum Weather {
RAINING,
SUNNY,
SNOWING,
}
enum Clothing {
RAIN_COAT,
SHIRT,
COAT,
}
function decideWhatToWear(weather: Weather): Clothing {
switch (weather) {
case Weather.RAINING:
return Clothing.RAIN_COAT;
case Weather.SUNNY:
return Clothing.SHIRT;
case Weather.SNOWING:
return Clothing.COAT;
}
}
const weather: Weather = Weather.RAINING as Weather;
const shouldWear: Clothing = decideWhatToWear(weather);
// This is constant and easy to read.
enum Weather {
RAINING,
SUNNY,
SNOWING,
}
enum Clothing {
RAIN_COAT,
SHIRT,
COAT,
}
const weather: Weather = Weather.RAINING as Weather;
const shouldWear: Clothing = ((weather: Weather) => {
switch (weather) {
case Weather.RAINING:
return Clothing.RAIN_COAT;
case Weather.SUNNY:
return Clothing.SHIRT;
case Weather.SNOWING:
return Clothing.COAT;
}
})(weather);
// This is interesting because it has the constant and most of the readability benifits that you saw in the previous file.
// But now there is no seperation between the logic and where it's being used.
// This makes it extremely easy to remove the code as one block.
// And because the logic is encapsulated, it can't be reused (wich may be desireable in some cases).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment