检查一个函数是否总是 returns 布尔值

Check that a function always returns boolean

我需要检查用户指定的谓词是否总是 returns 布尔值。示例代码如下所示:

let isMostlyBoolean = function (aPredicate) {

return ( typeof aPredicate(undefined) === 'boolean' &&
    typeof aPredicate(null) === 'boolean' &&
    typeof aPredicate(false) === 'boolean' &&
    typeof aPredicate(Number.NaN) === 'boolean' &&
    typeof aPredicate(256) === 'boolean' &&
    typeof aPredicate("text") === 'boolean' &&
    typeof aPredicate('s') === 'boolean' &&
    typeof aPredicate(Math.sqrt) === 'boolean' &&
    typeof aPredicate(Object) === 'boolean' &&
    typeof aPredicate(['x', 'y', 'z']) === 'boolean'
);

}

有效。有没有更简洁 and/or 有效的 aPredicate 检查方法?这里我们一一扫描所有可能的data types

_.isFunction(a) vs. typeof a === 'function'? javascript 讨论中所述,typeof 应该是可行的方法。知道如何以更花哨和可读的方式做到这一点吗?

Edit: Note that the test above is a kind of fuzzy logic. Function name was changed accordingly. See @georg comments and more below.

给出测试代码:

let prediLess = (x) => x<2;
let predicate = (x) => x || (x<2);

console.log("isMostlyBoolean(prediLess): ", isMostlyBoolean(prediLess));
console.log("isMostlyBoolean(predicate): ", isMostlyBoolean(predicate));

console.log("\nprediLess(undefined): ", prediLess(undefined));
console.log("prediLess(1): ", prediLess(1));
console.log("prediLess(Object): ", prediLess(Object));

console.log("\npredicate(undefined): ", predicate(undefined));
console.log("predicate(1): ", predicate(1));
console.log("predicate(Object): ", predicate(Object));

控制台输出为:

returnsBoolean(prediLess):  true
returnsBoolean(predicate):  false

prediLess(undefined):  false
prediLess(1):  true
prediLess(Object):  false

predicate(undefined):  false
predicate(1):  1
predicate(Object):  function Object() { [native code] }
 [undefined, null, NaN, 0, 1, "", "a", [], [1], {}].every(el => typeof aPredicate(el) === "boolean");

只需将所有可能的值存储在一个数组中并对其进行迭代并检查每个值是否合适。