Skip to content

Instantly share code, notes, and snippets.

@ddddxxx
Created September 28, 2018 07:59
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 ddddxxx/25a157d216c61df8b05c3c4edf3c43b5 to your computer and use it in GitHub Desktop.
Save ddddxxx/25a157d216c61df8b05c3c4edf3c43b5 to your computer and use it in GitHub Desktop.
Range+Clamp
extension Comparable {
func clamped(to range: ClosedRange<Self>) -> Self {
return max(min(self, range.upperBound), range.lowerBound)
}
func clamped(to range: PartialRangeFrom<Self>) -> Self {
return max(self, range.lowerBound)
}
func clamped(to range: PartialRangeThrough<Self>) -> Self {
return min(self, range.upperBound)
}
}
extension Strideable {
func clamped(to range: Range<Self>) -> Self {
guard !range.isEmpty else {
preconditionFailure("Range cannot be empty")
}
let closedRange = range.lowerBound...range.upperBound.advanced(by: -1)
return clamped(to: closedRange)
}
func clamped(to range: PartialRangeUpTo<Self>) -> Self {
// I don't think there's a way to check if the range is empty
let closedRange = ...range.upperBound.advanced(by: -1)
return clamped(to: closedRange)
}
}
extension BinaryFloatingPoint {
func clamped(to range: Range<Self>) -> Self {
guard !range.isEmpty else {
preconditionFailure("Range cannot be empty")
}
let closedRange = range.lowerBound...range.upperBound.nextDown
return clamped(to: closedRange)
}
func clamped(to range: PartialRangeUpTo<Self>) -> Self {
let closedRange = ...range.upperBound.nextDown
return clamped(to: closedRange)
}
}
extension Comparable {
mutating func clamp(to range: ClosedRange<Self>) {
self = clamped(to: range)
}
mutating func clamp(to range: PartialRangeThrough<Self>) {
self = clamped(to: range)
}
mutating func clamp(to range: PartialRangeFrom<Self>) {
self = clamped(to: range)
}
}
extension Strideable {
mutating func clamp(to range: Range<Self>) {
self = clamped(to: range)
}
mutating func clamp(to range: PartialRangeUpTo<Self>) {
self = clamped(to: range)
}
}
extension BinaryFloatingPoint {
mutating func clamp(to range: Range<Self>) {
self = clamped(to: range)
}
mutating func clamp(to range: PartialRangeUpTo<Self>) {
self = clamped(to: range)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment