In Redux, there is a “selector” library . It makes computing derived property from state more performance and thus encouraging minimal possible state. I think this fit very well into the current sub-state subscription.
I am not sure weather we can implement similar thing in Swift.But If its possible, I think its a good function to have in ReSwift.
@soapsign I agree.
If we want syntax like the following:
let shopItemsSelector: (AppState) -> [Item] = { state in return state.shop.items }
let taxPercentSelector: (AppState) -> Int = { state in return state.shop.taxPercent }
let subtotalSelector = createSelector(shopItemsSelector, { (items: [Item]) in
return items.reduce(0, combine: {$0 + $1.value})
})
let taxSelector = createSelector(subtotalSelector, taxPercentSelector, { (subtotal, taxPercent) in
return subtotal * (taxPercent / 100)
})
let totalSelector = createSelector(subtotalSelector, taxSelector, { (subtotal, tax) in
return subtotal + tax
})
Then there would need to be a createSelector() function, with X parameters. Something like this (example without any kind of memoization):
func createSelector<State, S1, R>(p1: (State) -> S1, _ returnFunc: (S1) -> R) -> (State) -> R {
return { (state) in
return returnFunc(p1(state))
}
}
func createSelector<State, S1, S2, R>(p1: (State) -> S1, _ p2: (State) -> S2, _ returnFunc: (S1, S2) -> R) -> (State) -> R {
return { (state) in
return returnFunc(p1(state), p2(state))
}
}
func createSelector<State, S1, S2, S3, R>(p1: (State) -> S1, _ p2: (State) -> S2, p3: (State) -> S3, _ returnFunc: (S1, S2, S3) -> R) -> (State) -> R {
return { (state) in
return returnFunc(p1(state), p2(state), p3(state))
}
}
Anyone else have a better way of doing this? I could throw up a simple project using something close to what you see above if you're interested in giving it a shot.
Created the project to get a better understanding of what kind of issues we might face. https://github.com/wpK/reswelect
Most helpful comment
@soapsign I agree.
If we want syntax like the following:
Then there would need to be a createSelector() function, with X parameters. Something like this (example without any kind of memoization):
Anyone else have a better way of doing this? I could throw up a simple project using something close to what you see above if you're interested in giving it a shot.