Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Array extension that insert an element n-times in the array with a gap between each element's insertion.
extension Array
{
/**
Insert an element n-times in the array
with a gap between each element's insertion.
```
var numbers: [String] = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ]
numbers.repeat("X", gap: 3, fromTheBeginning: false)
```
After the `repeat` function `numbers` array will be:
```
["1", "2", "3", "X", "4", "5", "6", "X", "7", "8", "9", "X", "10"]
```
- Parameters:
- element: New element
- gap: Distance between new element insertions
- fromTheBeginning: Insert the new element at 0 index.
- SeeAlso: `repeated(_:gap:fromTheBeginning:)` for non mutating version
*/
mutating func `repeat`(_ element: Element, gap: Int, fromTheBeginning: Bool = false)
{
let indexes: [Int] = (0..<(self.count / gap)).map({ ($0 + 1) * gap }).reversed()
for index in indexes
{
self.insert(element, at: index)
}
if fromTheBeginning
{
self.insert(element, at: 0)
}
}
/**
Create a copy of the current array and
insert an element n-times in the new array
with a gap between each element's insertion.
```
let numbers: [String] = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ]
let mixed_numbers: [String] = numbers.repeat("X", gap: 3, fromTheBeginning: false)
```
After the `repeat` function `mixed_numbers` array will be:
```
["1", "2", "3", "X", "4", "5", "6", "X", "7", "8", "9", "X", "10"]
```
- Parameters:
- element: New element
- gap: Distance between new element insertions
- fromTheBeginning: Insert the new element at 0 index.
- SeeAlso: `repeat(_:gap:fromTheBeginning:)` for mutating version
*/
func repeated(_ element: Element, gap: Int, fromTheBeginning: Bool = false) -> [Element]
{
var other: [Element] = [Element](self)
other.repeat(element, gap: gap, fromTheBeginning: fromTheBeginning)
return other
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.