Last active
December 8, 2017 17:04
-
-
Save ithinkihaveacat/6df589e77fa097b18ee36ff867ce71b2 to your computer and use it in GitHub Desktop.
Promise-compatible boolean AND and OR functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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