Author:
Map, Filter and Reduce⚓︎
Map-Filter-Reduce are well known as
Syntactic Sugar
, which is a term for syntax changes in computer programming which make it easier for humans to code. Also, it is aFan-in Fan-out
way to process multiple tasks.
Grammar⚓︎
Way1: Function⚓︎
Example⚓︎
Code⚓︎
way1.swift
import Foundation
func cook(food: String) -> String {
var transformedFood = ""
switch food {
case "🌽":
transformedFood = "🍿"
print(1)
case "🐮":
transformedFood = "🍔"
print(2)
case "🐔":
transformedFood = "🍳"
print(3)
default: transformedFood = food // remains uncooked
}
return transformedFood
}
func eat(food1: String, food2: String) -> String {
var transformedFood = "💩"
return transformedFood
}
func isVegetarian(dish: String) -> Bool {
return dish=="🍳"
}
//Map
let meals = ["🌽", "🐮", "🐔"].map(cook)
//Filter
let filtered_meals = meals.filter(isVegetarian)
//Reduce
let result = filtered_meals.reduce("",eat)
//Print
print(meals)
print(filtered_meals)
print(result)
Result⚓︎
Way2: Closure⚓︎
Example⚓︎
Realize the assert shown below with closure:
Q2.swift
for _ in 0...5 {
let foodNames = ["🍔": "hamburger", "🍟": "french fries", "🌽": "popcorn"]
var outcome = foodNames.map({...}).filter({}).reduce(...,{...})
outcome.removeFirst()
assert(
outcome == "Hamburger Popcorn" ||
outcome == "Popcorn Hamburger"
)
}
Code⚓︎
way2.swift
import Foundation
for _ in 0...5 {
let foodNames = ["🍔": "hamburger", "🍟": "french fries", "🌽": "popcorn"]
//Map
var mapped = foodNames.map({(key,value) -> String in return value.capitalized})
//Filter
var filterred = mapped.filter({(food:String) -> Bool in return !(food == "French Fries")})
//Reduce
var reduced = filterred.reduce("",{a, b in a + " " + b})
reduced.removeFirst()
var outcome = reduced
assert(
outcome == "Hamburger Popcorn" ||
outcome == "Popcorn Hamburger"
)
}
Result⚓︎
Way3: Using the built-in operator⚓︎
Example⚓︎
Realize the assert shown below with built-in operator:
Code⚓︎
way3.swift
import Foundation
let outcome = [2, 3, 5, 8].map( {$0 + 1} ).filter( {$0 != 5} ).reduce(1, *)
assert(outcome == 108)