Last active
March 15, 2021 00:35
-
-
Save jasdev/ec91fd5245c5aabe7a807b661f0ea2df to your computer and use it in GitHub Desktop.
`RangeReplaceableCollection.rotated(by:)` attempt w/ proper modulus.
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
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