Last active
May 8, 2019 07:54
-
-
Save AccordionGuy/61716adbf706801e2a496a12ff19526e to your computer and use it in GitHub Desktop.
Map, filter, and reduce in Swift, explained with emoji
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Map | |
func cook(_ item: String) -> String { | |
let cookupTable = [ | |
"๐ฎ": "๐", // Cow face -> burger | |
"๐": "๐", // Cow -> burger | |
"๐": "๐", // Ox -> meat on bone | |
"๐ท": "๐", // Pig face -> meat on bone | |
"๐ฝ": "๐", // Pig nose -> meat on bone | |
"๐": "๐", // Pig -> meat on bone | |
"๐": "๐", // Sheep -> meat on bone | |
"๐": "๐", // Goat -> meat on bone | |
"๐": "๐", // Chicken -> poultry leg | |
"๐ฆ": "๐", // Turkey -> poultry leg | |
"๐ธ": "๐", // Frog -> poultry leg (no frog leg emoji...yet) | |
"๐": "๐ฃ", // Fish -> sushi | |
"๐ ": "๐ฃ", // Tropical fish -> sushi | |
"๐ก": "๐ฃ", // Blowfish -> sushi | |
"๐": "๐ฃ", // Octopus -> sushi | |
"๐ ": "๐", // (Sweet) potato -> French fries | |
"๐ฝ": "๐ฟ", // Corn -> popcorn | |
"๐พ": "๐", // Rice -> cooked rice | |
"๐": "๐ฐ", // Strawberry -> shortcake | |
"๐": "๐ต", // Dried leaves -> tea | |
] | |
if let cookedFood = cookupTable[item] { | |
return cookedFood | |
} | |
else { | |
return "๐ฝ" // Empty plate | |
} | |
} | |
let cookedFood = ["๐ฎ", "๐ ", "โฝ๏ธ", "๐", "๐ฝ"].map { cook($0) } | |
cookedFood // ["๐", "๐", "๐ฝ", "๐", "๐ฟ"] | |
// Filter | |
func isVegetarian(_ item: String) -> Bool { | |
let vegetarianDishes = Set([ | |
"๐", // French fries | |
"๐ฟ", // Popcorn | |
"๐", // Cooked rice | |
"๐ฐ", // Shortcake | |
"๐ต", // Tea | |
]) | |
return vegetarianDishes.contains(item) | |
} | |
let meatFree = ["๐", "๐", "๐", "๐ฝ", "๐", "๐ฟ", "๐ฐ"].filter { isVegetarian($0) } | |
meatFree // ["๐", "๐ฟ", "๐ฐ"] | |
// Reduce | |
func eat(_ previous: String, _ current: String) -> String { | |
let qualifyingFood = Set([ | |
"๐", // Burger | |
"๐", // Meat on bone | |
"๐", // Poultry leg | |
"๐ฃ", // Sushi | |
"๐", // French fries | |
"๐ฟ", // Popcorn | |
"๐", // Cooked rice | |
"๐ฐ", // Shortcake | |
]) | |
if (previous == "" || previous == "๐ฉ") && qualifyingFood.contains(current) { | |
return "๐ฉ" // Poop | |
} | |
else { | |
return "" | |
} | |
} | |
let aftermath = ["๐", "๐", "๐", "๐ฟ"].reduce("", combine: eat) | |
aftermath // "๐ฉ" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment