Skip to content

Instantly share code, notes, and snippets.

@fitomad
Created March 14, 2018 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fitomad/3476d66991c1d513bfc2b503662e3052 to your computer and use it in GitHub Desktop.
Save fitomad/3476d66991c1d513bfc2b503662e3052 to your computer and use it in GitHub Desktop.
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