Skip to content
This repository has been archived by the owner on Jan 14, 2020. It is now read-only.

Commit

Permalink
Add util.negate
Browse files Browse the repository at this point in the history
This function takes an (asynchronous) function that is expected to
return a boolean and returns a new function which returns the inverse of
the original function.
  • Loading branch information
brianloveswords committed May 24, 2013
1 parent cb64e06 commit b25c022
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,4 +198,16 @@ util.isEmail = function isEmail(email) {
return reEmail.test(email);
};

util.negate = function negate(fn) {
return function () {
const args = [].slice.call(arguments);
const cb = args.pop();
args.push(function (err, result) {
if (err) return cb(err);
return cb(null, !result);
});
fn.apply(null, args);
};
};

module.exports = util;
10 changes: 10 additions & 0 deletions tests/util.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,13 @@ test('util.whitelist', function (t) {
t.same(list.exempt('AaaaaaaD'), true);
t.end();
});

test('util.negate', function (t) {
function asyncTrue(cb) {
cb(null, true);
};
util.negate(asyncTrue)(function (err, result) {
t.same(result, false);
t.end();
});
});

0 comments on commit b25c022

Please sign in to comment.