Skip to content

Instantly share code, notes, and snippets.

@bennokress
Last active June 24, 2017 17:34
Show Gist options
  • Save bennokress/e6cdc84bdfc898f76651c3e4386506c5 to your computer and use it in GitHub Desktop.
Save bennokress/e6cdc84bdfc898f76651c3e4386506c5 to your computer and use it in GitHub Desktop.
Extensions for Swift's Array type
extension Array {
// Usage: [1,2,3,4].shifted(by: 2) --> [3,4,1,2] or "hello".shifted(by: -1) --> "elloh"
func shifted(by shiftAmount: Int) -> Array {
guard self.count > 0, (shiftAmount % self.count) != 0 else { return self }
let moduloShiftAmount = shiftAmount % self.count
let effectiveShiftAmount = moduloShiftAmount < 0 ? moduloShiftAmount + self.count : moduloShiftAmount
let shift: (Int) -> Int = { return $0 + effectiveShiftAmount >= self.count ? $0 + effectiveShiftAmount - self.count : $0 + effectiveShiftAmount }
return self.enumerated().sorted(by: { shift($0.offset) < shift($1.offset) }).map { $0.element }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment