javascript - 检查函数是否始终返回 bool 值

标签 javascript predicate

我需要检查用户指定的谓词是否始终返回 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/

相关文章:

Javascript 对象不附加新属性

javascript - 在 Javascript 中查找范围内的值

java - 是否有与 .Net 中的 Predicate<T> 方法等效的 Java 1.5?

c# - 如何将谓词生成器与 linq2sql 和 OR 运算符一起使用

SQL:从谓词逻辑到 SQL SELECT

javascript - 对所有 div 使用一个 onchange javascript 函数

javascript - 使用javascript禁用iframe的重定向

java - (Predicate<? super String> s) 或 (String s)

python - Python 中的 Pointfree 函数组合

javascript - 如何通过使用 javascript 在屏幕上移动触摸来选择移动网络浏览器上的文本?