Skip to content

Instantly share code, notes, and snippets.

@bennokress
Created May 17, 2020 15:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennokress/a12f967e809575be3820c76578640143 to your computer and use it in GitHub Desktop.
Save bennokress/a12f967e809575be3820c76578640143 to your computer and use it in GitHub Desktop.
import Foundation
extension Array {
func shifted(by shiftAmount: Int) -> Array<Element> {
// 1
guard self.count > 0, (shiftAmount % self.count) != 0 else { return self }
// 2
let moduloShiftAmount = shiftAmount % self.count
let negativeShift = shiftAmount < 0
let effectiveShiftAmount = negativeShift ? moduloShiftAmount + self.count : moduloShiftAmount
// 3
let shift: (Int) -> Int = { return $0 + effectiveShiftAmount >= self.count ? $0 + effectiveShiftAmount - self.count : $0 + effectiveShiftAmount }
// 4
return self.enumerated().sorted(by: { shift($0.offset) < shift($1.offset) }).map { $0.element }
}
mutating func shifting(by shiftAmount: Int) {
// 1
guard self.count > 0, (shiftAmount % self.count) != 0 else { return }
// 2
let moduloShiftAmount = shiftAmount % self.count
let negativeShift = shiftAmount < 0
let effectiveShiftAmount = negativeShift ? moduloShiftAmount + self.count : moduloShiftAmount
// 3
let copy = self
let shift: (Int) -> Int = { return $0 + effectiveShiftAmount >= copy.count ? $0 + effectiveShiftAmount - copy.count : $0 + effectiveShiftAmount }
// 4
self = self.enumerated().sorted(by: { shift($0.offset) < shift($1.offset) }).map { $0.element }
}
}
let colorArray = [
UIColor.red,
UIColor.orange,
UIColor.yellow,
UIColor.green,
UIColor.blue
]
let shiftedColorArray = [
UIColor.green,
UIColor.blue,
UIColor.red,
UIColor.orange,
UIColor.yellow
]
colorArray.shifted(by: 2) == shiftedColorArray // returns true
[1,2,3,4,5,6,7].shifted(by: -23) // returns [3,4,5,6,7,1,2]
var testArray = [1,2,3,4,5,6,7]
testArray.shifting(by: -23)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment