Skip to content

Commit

Permalink
Migrated to clamped(to:) from min(max. Makes it much more readable (#717
Browse files Browse the repository at this point in the history
)

Signed-off-by: Tim Bert <[email protected]>
  • Loading branch information
timbms committed Nov 7, 2023
1 parent 0a5a287 commit c600086
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 3 deletions.
19 changes: 19 additions & 0 deletions OpenHABCore/Sources/OpenHABCore/Util/Comparable.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright (c) 2010-2023 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0

import Foundation

// Idea taken from https://twitter.com/alexiscreuzot/status/1635489793294454784?s=61&t=8ECwUy6QFS5UxjAFZzZ-hw
public extension Comparable {
func clamped(to limits: ClosedRange<Self>) -> Self {
min(max(self, limits.lowerBound), limits.upperBound)
}
}
2 changes: 1 addition & 1 deletion openHAB/SliderUITableViewCell.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class SliderUITableViewCell: GenericUITableViewCell {
private func adj(_ raw: Double) -> Double {
var valueAdjustedToStep = Double(floor(Float(((raw - widget.minValue))) / step) * step)
valueAdjustedToStep += widget.minValue
return min(max(valueAdjustedToStep, widget.minValue), widget.maxValue)
return valueAdjustedToStep.clamped(to: widget.minValue ... widget.maxValue)
}

private func adjustedValue() -> Double {
Expand Down
2 changes: 1 addition & 1 deletion openHABWatch/Model/ObservableOpenHABWidget.swift
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ class ObservableOpenHABWidget: NSObject, MKAnnotation, Identifiable, ObservableO
private func adj(_ raw: Double) -> Double {
var valueAdjustedToStep = floor((raw - minValue) / step) * step
valueAdjustedToStep += minValue
return min(max(valueAdjustedToStep, minValue), maxValue)
return valueAdjustedToStep.clamped(to: minValue ... maxValue)
}
}

Expand Down
2 changes: 1 addition & 1 deletion openHABWatch/Views/Utils/ColorSelection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ struct ColorSelection: View {

/// Prevent the draggable element from going over its limit
func limitDisplacement(_ value: Double, _ limit: CGFloat, _ state: CGFloat) -> CGFloat {
max(0, min(limit, CGFloat(value) * limit + state))
(CGFloat(value) * limit + state).clamped(to: 0 ... limit)
}

/// Prevent the draggable element from going beyond the circle
Expand Down

0 comments on commit c600086

Please sign in to comment.