Skip to content

Commit

Permalink
Merge pull request #9 from RougeWare/feature/Swift-currentAverageOrNil
Browse files Browse the repository at this point in the history
Added `currentAverageOrNil`
  • Loading branch information
KyNorthstar authored Apr 6, 2021
2 parents 376a908 + af8f5c1 commit 28b0692
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Tests/EfficientAveragerTests/testbench.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,40 @@ final class Testbench: XCTestCase {

func testExample() {
var a = Averager<Double>(startingNumber: 13)
XCTAssertEqual(1, a.timesAveraged)
XCTAssertEqual(13, a.currentAverageOrNil)
XCTAssertEqual( 13.0 , a.currentAverage)
a.average(3)
XCTAssertEqual( 8.0 , a.currentAverage)
a.average(5, 12, 8, 7.3)
XCTAssertEqual( 8.05 , a.currentAverage, accuracy: 0.001)

var b = Averager<Double>()
XCTAssertEqual(b.currentAverage, 0)
XCTAssertEqual(b.timesAveraged, 0)
XCTAssertNil(b.currentAverageOrNil)
XCTAssertEqual( 0.0 , b.currentAverage)
b.average(13)
XCTAssertEqual( 13.0 , b.currentAverage)
b.average(55, 712.197, 18, 99)
XCTAssertEqual(179.439 , b.currentAverage, accuracy: 0.001)

var c = Averager<Double>()
XCTAssertEqual(c.currentAverage, 0)
XCTAssertEqual(c.timesAveraged, 0)
XCTAssertNil(c.currentAverageOrNil)
c.average(-2147483648, 2147483647, 2147483647, -2147483648)
XCTAssertEqual( -0.5 , c.currentAverage)

XCTAssertEqual( 6 , a.timesAveraged)
XCTAssertEqual( 5 , b.timesAveraged)
XCTAssertEqual( 4 , c.timesAveraged)


c.clear()
XCTAssertEqual(c.currentAverage, 0)
XCTAssertEqual(c.timesAveraged, 0)
XCTAssertNil(c.currentAverageOrNil)
}

static let allTests = [
Expand Down
13 changes: 13 additions & 0 deletions lib/Averager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ public extension Averager {


/// Resets this averager to a state before any number has been averaged
@discardableResult
mutating func clear() -> Averager<Number> {
currentAverage = 0.0
timesAveraged = 0
Expand All @@ -126,6 +127,18 @@ public extension Averager {



public extension Averager {

/// If any numbers have been averaged, this returns the current average. Else, if no numbers have yet been averaged, this returns `nil`
var currentAverageOrNil: Number? {
timesAveraged > 0
? currentAverage
: nil
}
}



/// Mutates the averager on the left-hand side so that the number on the right-hand side is averaged into it
///
/// - Parameters:
Expand Down

0 comments on commit 28b0692

Please sign in to comment.