Skip to content

Instantly share code, notes, and snippets.

@MartinJNash
Created December 30, 2014 03:48
Show Gist options
  • Save MartinJNash/0885842179430c754caa to your computer and use it in GitHub Desktop.
Save MartinJNash/0885842179430c754caa to your computer and use it in GitHub Desktop.
Repetition of array elements
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