Skip to content

Commit

Permalink
Add ArrayExtension
Browse files Browse the repository at this point in the history
  • Loading branch information
aromanov91 committed Jul 25, 2023
1 parent 59707da commit 41fb600
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions Sources/OversizeCore/Extensions/Swift/Array+Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,33 @@ extension Array: RawRepresentable where Element: Codable {
return result
}
}

public extension BidirectionalCollection where Iterator.Element: Equatable {
func after(_ item: Iterator.Element, loop: Bool = false) -> Element? {
if let itemIndex = firstIndex(of: item) {
let lastItem: Bool = (index(after: itemIndex) == endIndex)
if loop, lastItem {
return first
} else if lastItem {
return nil
} else {
return self[index(after: itemIndex)]
}
}
return nil
}

func before(_ item: Iterator.Element, loop: Bool = false) -> Element? {
if let itemIndex = firstIndex(of: item) {
let firstItem: Bool = (itemIndex == startIndex)
if loop, firstItem {
return last
} else if firstItem {
return nil
} else {
return self[index(before: itemIndex)]
}
}
return nil
}
}

0 comments on commit 41fb600

Please sign in to comment.