Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Map, filter, and reduce in Swift, explained with emoji
// 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