Skip to content

Commit

Permalink
Add property.filter
Browse files Browse the repository at this point in the history
  • Loading branch information
iv-mexx committed Dec 30, 2017
1 parent bdd8ea0 commit fa436b8
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# master
*Please add new entries at the top.*

1. New property operator: `filter` (#586, kudos to @iv-mexx)

# 3.1.0-rc.1
1. Fixed a scenario of downstream interruptions being dropped. (#577, kudos to @andersio)

Expand Down
14 changes: 14 additions & 0 deletions Sources/Property.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,20 @@ extension PropertyProtocol {
return lift { $0.map(keyPath) }
}

/// Passes only the values of the property that pass the given predicate
/// to a new property.
///
/// - parameters:
/// - initial: A `Property` always needs a `value`. The initial `value` is necessary in case the
/// predicate excludes the first (or all) `value`s of this `Property`
/// - predicate: A closure that accepts value and returns `Bool` denoting
/// whether current `value` of this `Property` has passed the test.
///
/// - returns: A property that holds only values from `self` passing the given predicate.
public func filter(initial: Value, _ predicate: @escaping (Value) -> Bool) -> Property<Value> {
return Property(initial: initial, then: self.producer.filter(predicate))
}

/// Combines the current value and the subsequent values of two `Property`s in
/// the manner described by `Signal.combineLatest(with:)`.
///
Expand Down
37 changes: 37 additions & 0 deletions Tests/ReactiveSwiftTests/PropertySpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -750,6 +750,43 @@ class PropertySpec: QuickSpec {
}
}

describe("filter") {
it("should only receive values that pass the predicate") {
let property = MutableProperty(1)
let filteredProperty = property
.filter(initial: 0) { $0 > 0 }
expect(filteredProperty.value) == 1

property.value = 0
expect(filteredProperty.value) == 1

property.value = 2
expect(filteredProperty.value) == 2

property.value = -5
expect(filteredProperty.value) == 2

property.value = 3
expect(filteredProperty.value) == 3
}

it("should behave correctly if the filter excludes the initial value") {
let property = MutableProperty(1)
let filteredProperty = property
.filter(initial: 0) { $0 < 0 }
expect(filteredProperty.value) == 0

property.value = 2
expect(filteredProperty.value) == 0

property.value = -2
expect(filteredProperty.value) == -2

property.value = 0
expect(filteredProperty.value) == -2
}
}

describe("combineLatest") {
var property: MutableProperty<String>!
var otherProperty: MutableProperty<String>!
Expand Down

0 comments on commit fa436b8

Please sign in to comment.