Created
December 30, 2014 03:48
-
-
Save MartinJNash/0885842179430c754caa to your computer and use it in GitHub Desktop.
Repetition of array elements
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 { | |
/// [1, 2, 3] by 2 produces: [1, 1, 2, 2, 3, 3] | |
func replicated(times: UInt) -> Array { | |
return self.reduce([], combine: { mem, curr in | |
mem + Array(count: Int(times), repeatedValue: curr) | |
}) | |
} | |
/// [1, 2, 3] by 2 produces: [1, 2, 3, 1, 2, 3] | |
func repeated(times: UInt) -> Array { | |
var mem: [Element] = [] | |
for x in 0..<times { | |
mem += self | |
} | |
return mem | |
} | |
} | |
[1, 3].replicated(3) | |
[1, 2].repeated(3) | |
["a", "b"].replicated(2) | |
["a", "b"].repeated(2) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment