I'm working on a publisher for Swift/Combine
Given a stream of inputs, I want to record the max value. If the next number is lower, take one from the last recorded max value and emit that.
Input: [1,2,3,4,5,2,3,3,1]
Output: [1,2,3,4,5,4,3,3,2]
I can do this easily with the following code, however, I really don't like the instance variable
var lastMaxInstanceValue: Float = 0
publisher
.map { newValue
if newValue > lastMaxInstanceValue {
lastMaxInstanceValue = newValue
} else {
lastMaxInstanceValue = max(0, lastMaxInstanceValue - 1)
}
}
.assign(to: \.percentage, on: self)
.store(in: &cancellables)
So I wrote a publisher/subscriber here which encapsulates the map
part above:
https://github.com/nthState/FallingMaxPublisher
With my publisher, the code turns into:
publisher
.fallingMax()
.assign(to: \.percentage, on: self)
.store(in: &cancellables)
My question is, is my GitHub publisher necessary? Can the value I want be calculated without having the extra variable?