In my last article, I posted this graphic, which uses emoji to make it easier to understand what the map
, filter
, and reduce
functions do:
Since then, I’ve been asked by a couple of friends if what’s in the graphic is just pseudocode or if it could actually be implemented. I told them it was the latter, and here’s my implementation in Swift:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
// 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 == "๐ฉ" |
I put this into a Swift playground, which you can copy from this Gist or download here.
2 replies on “Demonstrating map, filter, and reduce in Swift using food emoji”
[…] Demonstrating map, filter, and reduce in Swift using food emoji […]
[…] I didnโt want to stop at just making a graphic based on Steven Luscherโs tweet โ I wanted to build on it by making it real! So I implemented these emoji functions in Swift… […]