我需要检查用户指定的谓词是否始终返回 bool 值。示例代码如下所示:
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'
);
}
有效。是否有更简洁和/或更有效的 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");
只需将所有可能的值存储在一个数组中,然后迭代它并检查每个值是否适合。
关于javascript - 检查函数是否始终返回 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48866444/