Skip to content

Commit

Permalink
Merge pull request #6 from daehn/feature/return-if-count-changed
Browse files Browse the repository at this point in the history
Return whether or not the count changed
  • Loading branch information
daehn authored Sep 15, 2017
2 parents 397aa51 + ad89c71 commit 04a2b7c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
5 changes: 4 additions & 1 deletion CountedSet/CountedSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,18 @@ public struct CountedSet<Element : Hashable> : ExpressibleByArrayLiteral {
return count(for: member)
}

public mutating func setCount(_ count: Int, for element: Element) {
@discardableResult public mutating func setCount(_ count: Int, for element: Element) -> Bool {
precondition(count >= 0, "Count has to be positive")
guard count != countByElement[element] else { return false }

if count > 0 && !contains(element) {
backing.insert(element)
}
countByElement[element] = count
if count <= 0 {
backing.remove(element)
}
return true
}

public func mostFrequent() -> ElementWithCount? {
Expand Down
18 changes: 16 additions & 2 deletions CountedSetTests/CountedSetTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -261,16 +261,30 @@ class CountedSetTests: XCTestCase {
// given
sut = CountedSet(arrayLiteral: "Foo", "Bar")
// when
sut.setCount(3, for: "Foo")
XCTAssert(sut.setCount(3, for: "Foo"))
// then
XCTAssertEqual(sut.count(for: "Foo"), 3)
}

func testThatItReturnsFalseWhenSettingExistingCount() {
// given
sut = CountedSet(arrayLiteral: "Foo", "Bar", "Foo")
// then
XCTAssertFalse(sut.setCount(2, for: "Foo"))
}

func testThatItReturnsTrueWhenSettingCountForElementWithDifferentExistingCount() {
// given
sut = CountedSet(arrayLiteral: "Foo", "Bar")
// then
XCTAssert(sut.setCount(2, for: "Foo"))
}

func testThatItRemovesElementFrombackingStoreWhenSettingCountForContainedElementToZero() {
// given
sut = CountedSet(arrayLiteral: "Foo", "Bar")
// when
sut.setCount(0, for: "Foo")
XCTAssert(sut.setCount(0, for: "Foo"))
// then
XCTAssertFalse(sut.contains("Foo"))
XCTAssertEqual(sut.count(for: "Foo"), 0)
Expand Down

0 comments on commit 04a2b7c

Please sign in to comment.