Schafkopf-Server/Sources/App/Extensions/Array+Extensions.swift

69 lines
1.5 KiB
Swift
Raw Normal View History

2021-12-01 22:48:10 +01:00
import Foundation
extension Array {
2021-12-18 15:08:43 +01:00
func at(_ index: Int) -> Element? {
guard index < count else {
return nil
}
return self[index]
}
func rotatedByOne() -> [Element] {
guard !isEmpty else {
return []
}
return self[1...] + [self[0]]
}
mutating func rotateByOne() {
guard !isEmpty else {
return
}
append(removeFirst())
}
2021-12-01 22:48:10 +01:00
func rotated(toStartAt index: Int) -> [Element] {
guard index != 0 else {
return self
}
return Array(self[index..<count] + self[0..<index])
}
2021-12-06 11:43:30 +01:00
func sorted<T>(by converting: (Element) -> T) -> [Element] where T: Comparable {
sorted { converting($0) < converting($1) }
}
2021-12-01 22:48:10 +01:00
}
2021-12-18 15:08:43 +01:00
extension Array where Element: Equatable {
func index(of element: Element) -> Index {
firstIndex(of: element)!
}
}
extension Array where Element: Player {
var names: [PlayerName] {
map { $0.name }
}
func index(of player: PlayerName) -> Int {
firstIndex { $0.name == player }!
}
func player(named name: PlayerName) -> Element? {
first { $0.name == name }
}
func contains(player: PlayerName) -> Bool {
contains { $0.name == player }
}
func next(after player: Element) -> Element {
let i = index(of: player)
let newIndex = (i + 1) % maximumPlayersPerTable
return self[newIndex]
}
}