From af8f5c1bb1f0b51cd2a4663d647c8f5a06779b41 Mon Sep 17 00:00:00 2001 From: Ben Leggiero Date: Mon, 5 Apr 2021 21:56:50 -0600 Subject: [PATCH] Added `currentAverageOrNil` Also made `clear()`'s return discardable --- Tests/EfficientAveragerTests/testbench.swift | 14 ++++++++++++++ lib/Averager.swift | 13 +++++++++++++ 2 files changed, 27 insertions(+) diff --git a/Tests/EfficientAveragerTests/testbench.swift b/Tests/EfficientAveragerTests/testbench.swift index 73d2244..31d7114 100644 --- a/Tests/EfficientAveragerTests/testbench.swift +++ b/Tests/EfficientAveragerTests/testbench.swift @@ -5,6 +5,8 @@ final class Testbench: XCTestCase { func testExample() { var a = Averager(startingNumber: 13) + XCTAssertEqual(1, a.timesAveraged) + XCTAssertEqual(13, a.currentAverageOrNil) XCTAssertEqual( 13.0 , a.currentAverage) a.average(3) XCTAssertEqual( 8.0 , a.currentAverage) @@ -12,6 +14,9 @@ final class Testbench: XCTestCase { XCTAssertEqual( 8.05 , a.currentAverage, accuracy: 0.001) var b = Averager() + XCTAssertEqual(b.currentAverage, 0) + XCTAssertEqual(b.timesAveraged, 0) + XCTAssertNil(b.currentAverageOrNil) XCTAssertEqual( 0.0 , b.currentAverage) b.average(13) XCTAssertEqual( 13.0 , b.currentAverage) @@ -19,12 +24,21 @@ final class Testbench: XCTestCase { XCTAssertEqual(179.439 , b.currentAverage, accuracy: 0.001) var c = Averager() + 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 = [ diff --git a/lib/Averager.swift b/lib/Averager.swift index 9268e8c..1b0ec0d 100644 --- a/lib/Averager.swift +++ b/lib/Averager.swift @@ -117,6 +117,7 @@ public extension Averager { /// Resets this averager to a state before any number has been averaged + @discardableResult mutating func clear() -> Averager { currentAverage = 0.0 timesAveraged = 0 @@ -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: