小编mor*_*zko的帖子

检查函数是否总是返回布尔值

我需要检查用户指定的谓词总是返回一个布尔值.示例代码如下所示:

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'
);

}
Run Code Online (Sandbox Code Playgroud)

哪个有效.有更整洁和/或更有效的aPredicate检查方式吗?在这里,我们逐个扫描所有可能的数据类型.

_.isFunction(a)与==='function'的类型所述?javascript讨论typeof应该是要走的路.任何想法如何以更花哨和可读的方式做到这一点?

编辑:注意上面的测试是一种模糊逻辑.功能名称已相应更改.请参阅下面的@georg评论等.

鉴于测试代码:

let prediLess = (x) => x<2; …
Run Code Online (Sandbox Code Playgroud)

javascript predicate

2
推荐指数
1
解决办法
85
查看次数

标签 统计

javascript ×1

predicate ×1