Skip to content

Instantly share code, notes, and snippets.

@clohr
Last active October 4, 2015 15:40
Show Gist options
  • Save clohr/263368c6494d63296d79 to your computer and use it in GitHub Desktop.
Save clohr/263368c6494d63296d79 to your computer and use it in GitHub Desktop.
safeDOM
const logger = R.compose(
R.bind(console.log, console),
R.concat('Missing selector '),
R.flip(R.identity)
);
const mapCb = (x) => console.log(x.textContent);
const mapper = R.map(mapCb);
const validate = R.ifElse(
R.equals(S.Nothing()),
logger,
mapper
);
const queryDOM = R.compose(
S.toMaybe,
R.bind(document.querySelector, document)
);
const safeQuery = R.converge(
validate,
queryDOM,
R.identity
);
safeQuery('.modal');
@davidchase
Copy link

What are your thoughts on a little point-free style?

var warn = R.bind(console.warn, console);
var log = R.bind(console.log, console);
var queryCSS = R.bind(document.querySelector, document);
var maybeQuery = R.compose(S.toMaybe, queryCSS);
var noSelector = R.compose(S.Nothing, warn, R.concat('Missing selector: '), R.flip(R.identity));

var safeQuery = R.converge(R.ifElse(R.equals(S.Nothing()), noSelector, R.identity), maybeQuery, R.identity)

safeQuery('.container').map(log); 
// => <div class="container"></div>

safeQuery('.containers').map(log); 
// => ⚠ Missing selector: .containers, will use the above warn logger since returning Nothing

@clohr
Copy link
Author

clohr commented Sep 7, 2015

I like it. I actually started with the ifElse, but keep forgetting about R.concat. I'm going to start a repo and add you as a contributor so we can polish this thing up and publish it.

@davidchase
Copy link

yeah probably could be cleaned up, the 1st thought was to create reusable functions where possible for example some may not need to signify to the implementors that the specific selector is missing... etc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment