Skip to content

Instantly share code, notes, and snippets.

@ithinkihaveacat
Last active December 8, 2017 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ithinkihaveacat/6df589e77fa097b18ee36ff867ce71b2 to your computer and use it in GitHub Desktop.
Save ithinkihaveacat/6df589e77fa097b18ee36ff867ce71b2 to your computer and use it in GitHub Desktop.
Promise-compatible boolean AND and OR functions
// Not completely sure these do the right thing on reject...
function pand(...args) {
return args.length != 0 ? new Promise((resolve, reject) => {
let [tc, fc] = [0, 0];
function f(v) {
tc += v ? 1 : 0;
fc += v ? 0 : 1;
if (tc == args.length) resolve(true);
if (fc == 1) resolve(false);
}
args.forEach(v => Promise.resolve(v).then(f, reject));
}) : Promise.resolve(true);
}
function por(...args) {
return args.length != 0 ? new Promise((resolve, reject) => {
let [tc, fc] = [0, 0];
function f(v) {
tc += v ? 1 : 0;
fc += v ? 0 : 1;
if (tc == 1) resolve(true);
if (fc == args.length) resolve(false);
}
args.forEach(v => Promise.resolve(v).then(f, reject));
}) : Promise.resolve(true);
}
const T = Promise.resolve(true);
const F = Promise.resolve(false);
pand(T, T).then(console.log); // true
por(T, F).then(console.log); // true
pand(por(F, T), F).then(console.log); // false
// can also mix Promises and primitive types
por(por(true, false), F).then(console.log); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment