[英]Check that a function always returns boolean
I need to check that a user specified predicate always returns a boolean value. 我需要检查用户指定的谓词是否始终返回布尔值。 Sample code looks like this:
示例代码如下所示:
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'
);
}
which works. 哪个有效。 Is there a more neat and/or efficient way of
aPredicate
check-up? 有没有更简洁和/或更有效的
aPredicate
检查方法? Here we scan all possible data types one by one. 在这里,我们一一扫描所有可能的数据类型 。
As stated in _.isFunction(a) vs. typeof a === 'function'? 如_.isFunction(a)与typeof a ==='function'中所述? javascript discussion the
typeof
should be the way to go. javascript讨论
typeof
应该是要走的路。 Any idea how to do that in more fancy and readable way? 任何想法如何更花哨和可读性的方式做到这一点?
Edit: Note that the test above is a kind of fuzzy logic.
编辑:请注意,上面的测试是一种模糊逻辑。 Function name was changed accordingly.
功能名称已相应更改。 See @georg comments and more below.
请参阅下面的@georg评论和更多内容。
Given the test code: 给出测试代码:
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));
the console output is: 控制台输出为:
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");
只需将所有可能的值存储在数组中并对其进行迭代,然后检查每个值是否适合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.