Skip to content

Instantly share code, notes, and snippets.

@stefanfrede
Last active June 9, 2016 04:44
Show Gist options
  • Save stefanfrede/3f83f68c756998e43cb39a350a709e2c to your computer and use it in GitHub Desktop.
Save stefanfrede/3f83f68c756998e43cb39a350a709e2c to your computer and use it in GitHub Desktop.
Maybe takes a function and checks for nothing.
/**
* Do nothing when given nothing.
*/
const maybe = (fn) =>
function (...args) {
if (args.length === 0) {
return;
} else {
for (let arg of args) {
if (arg == null) {
return;
}
}
return fn.apply(this, args);
}
};
/**
* Examples:
*/
maybe((a, b, c) => a + b + c)(1, 2, 3);
//=> 6
maybe((a, b, c) => a + b + c)(1, null, 3);
//=> undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment