Created
April 13, 2018 14:17
-
-
Save ktilcu/d406301d47511bf45c19bb1fe3eee7e1 to your computer and use it in GitHub Desktop.
Maybes with one null check
This file contains hidden or 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
| // type alias DOM = Object // unknown structure, defined by Cheerio | |
| // type alias Selector = String // like a jquery selector (e.g., '#omg') | |
| // selectAll :: Selector -> DOM -> List DOM | |
| const selectAll = R.curry((sel, dom) => { | |
| const res = dom(sel); | |
| return R.map(cheerio, res.toArray()); | |
| }); | |
| // selectFirst :: Selector -> DOM -> Maybe DOM | |
| const selectFirst = R.curry((sel, dom) => | |
| R.pipe(selectAll(sel), R.head, S.toMaybe)(dom) | |
| ); | |
| selectFirst('.product', productsDom) // returns a Maybe DOM | |
| .map(text) // if the DOM is there it gets the text otherwise it's a noop | |
| .map(processText) // if the DOM was there we can process the text however we want | |
| /********** Imperative equivalent **************/ | |
| // selectFirst :: Selector -> DOM -> Maybe DOM | |
| const selectFirst = R.curry((sel, dom) => | |
| R.pipe(selectAll(sel), R.head)(dom) | |
| ); | |
| var product = selectFirst('.product', productsDom); | |
| if (product) { | |
| processText(text(product)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment