Skip to content

Instantly share code, notes, and snippets.

@jasdev
Last active March 15, 2021 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasdev/ec91fd5245c5aabe7a807b661f0ea2df to your computer and use it in GitHub Desktop.
Save jasdev/ec91fd5245c5aabe7a807b661f0ea2df to your computer and use it in GitHub Desktop.
`RangeReplaceableCollection.rotated(by:)` attempt w/ proper modulus.
infix operator %%: MultiplicationPrecedence // To match `%`’s precedence
// (https://developer.apple.com/documentation/swift/swift_standard_library/operator_declarations#2881142).
func %%<T: BinaryInteger>(_ lhs: T, _ rhs: T) -> T {
let remainder = lhs % rhs
guard remainder < 0 else { return remainder }
return rhs > 0 ? // Note, while it seems like this ternary can be reduced down to either
// `return remainder + abs(rhs)` or `return remainder + rhs.magnitude`, that‘d require `T`
// to conform to `SignedNumeric` or for `T.Magnitude == T` and I figured we could keep generality.
remainder + rhs :
remainder - rhs
}
extension RangeReplaceableCollection where Index: BinaryInteger { // To allow for `%%`ing on `Index`.
func rotated(by offset: Index) -> SubSequence {
guard !isEmpty else { return .init() }
let shiftPoint = offset %% endIndex // Updating the implementation to use `%%`.
return self[shiftPoint...] + self[..<shiftPoint]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment