Created
August 17, 2017 17:18
-
-
Save dtinth/e4329efd3882f926a134cb8a746d57a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const memoizeArraySelector = (baseSelector) => { | |
let _last = [ ] | |
return (state) => { | |
const result = baseSelector(state) | |
if (arrayEquals(result, _last)) return _last | |
_last = result | |
return result | |
} | |
} | |
export const mapSelector = f => baseSelector => createSelector(baseSelector, f) | |
export const mapSelectorForArray = f => baseSelector => memoizeArraySelector(mapSelector(f)(baseSelector)) | |
export const filteredBy = predicate => mapSelectorForArray(data => _.filter(data, predicate)) | |
export const rejectedBy = predicate => mapSelectorForArray(data => _.reject(data, predicate)) | |
export const sortedBy = sortBy => mapSelectorForArray(data => _.sortBy(data, sortBy)) | |
export const sortedByOrder = (sortByOrder, direction) => mapSelectorForArray(data => _.orderBy(data, sortByOrder, direction)) |
-
About flow type, yep I agreed that Flow/TypeScript type notation makes it look very scary.
-
About making
memoizeSelector
work with both array and non-array, I like it a lot. -
Yes, it can be a Reader monad. For example, using
createSelector
to combine selectors can be considered a monadic operation:// Assume a selector is a fantasy-land monad instead of a (s => a) function. const combine2 = s1 => s2 => f => s1.chain(v1 => s2.map(v2 => f(v1, v2)))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
By the way, I really like your idea having selector as a Functor. I have never thought about it before.
(actually, to think about it, this is not just a functor but can make it a Reader monad isn't it?)
And if we are able to use pipeline operator
|>
it would be even cooler.