Skip to content

Commit

Permalink
Add .clampedZeroToHundred (#12)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <[email protected]>
  • Loading branch information
EvanHahn and sindresorhus committed Sep 27, 2022
1 parent c517493 commit cc83668
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Sources/Percentage/Percentage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,30 @@ public struct Percentage: Hashable, Codable {
*/
public var fraction: Double { rawValue / 100 }

/**
Clamp the percentage to a value between 0% and 100%.
```
110%.clampedZeroToHundred
//=> 100%
-1%.clampedZeroToHundred
//=> 0%
60%.clampedZeroToHundred
//=> 60%
```
*/
public var clampedZeroToHundred: Self {
if rawValue > 100 {
return 100%
} else if rawValue < 0 {
return 0%
} else {
return self
}
}

/**
Create a `Percentage` from a `BinaryFloatingPoint`, for example, `Double` or `CGFloat`.
Expand Down
6 changes: 6 additions & 0 deletions Tests/PercentageTests/PercentageTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ final class PercentageTests: XCTestCase {
XCTAssertTrue(30% > 25%)
}

func testClampedZeroToHundred() {
XCTAssertEqual(101%.clampedZeroToHundred, 100%)
XCTAssertEqual((-1%).clampedZeroToHundred, 0%)
XCTAssertEqual(40%.clampedZeroToHundred, 40%)
}

func testPercentageOf() {
XCTAssertEqual(50%.of(200), 100)
XCTAssertEqual(50%.of(201), 100)
Expand Down
3 changes: 3 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ Percentage(fraction: 0.5)
10%.rawValue
//=> 10

110%.clampedZeroToHundred
//=> 100%

print("\(1%)")
//=> "1%"

Expand Down

0 comments on commit cc83668

Please sign in to comment.