Last active
June 24, 2017 17:34
-
-
Save bennokress/e6cdc84bdfc898f76651c3e4386506c5 to your computer and use it in GitHub Desktop.
Extensions for Swift's Array type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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