Last active
January 2, 2019 22:59
-
-
Save ijoshsmith/af327c43395859567d0d to your computer and use it in GitHub Desktop.
Cross-joining two Swift arrays
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
extension Array | |
{ | |
func crossJoin<E, R>( | |
array: [E], | |
joiner: (t: T, e: E) -> R?) | |
-> [R] | |
{ | |
return arrayCrossJoin(self, array, joiner) | |
} | |
} | |
/** | |
Executes the `joiner` closure for every combination | |
of elements between `aArray` and `bArray` and returns | |
the resulting objects in the order they were created. | |
*/ | |
func arrayCrossJoin<A, B, R>( | |
aArray: [A], | |
bArray: [B], | |
joiner: (a: A, b: B) -> R?) | |
-> [R] | |
{ | |
var results = [R]() | |
for a in aArray | |
{ | |
for b in bArray | |
{ | |
if let result = joiner(a: a, b: b) | |
{ | |
results.append(result) | |
} | |
} | |
} | |
return results | |
} | |
let letters = ["A", "B", "C"] | |
let numbers = [1, 2] | |
let dictionaries = letters.crossJoin(numbers) { [$0: $1] } | |
println(dictionaries) | |
// Prints: [[A: 1], [A: 2], [B: 1], [B: 2], [C: 1], [C: 2]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment