Skip to content

Instantly share code, notes, and snippets.

@ktilcu
Created April 13, 2018 14:17
Show Gist options
  • Select an option

  • Save ktilcu/d406301d47511bf45c19bb1fe3eee7e1 to your computer and use it in GitHub Desktop.

Select an option

Save ktilcu/d406301d47511bf45c19bb1fe3eee7e1 to your computer and use it in GitHub Desktop.
Maybes with one null check
// 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