mor*_*zko 2 javascript predicate
我需要检查用户指定的谓词总是返回一个布尔值.示例代码如下所示:
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;
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));
Run Code Online (Sandbox Code Playgroud)
控制台输出是:
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] }
Run Code Online (Sandbox Code Playgroud)
[undefined, null, NaN, 0, 1, "", "a", [], [1], {}].every(el => typeof aPredicate(el) === "boolean");
Run Code Online (Sandbox Code Playgroud)
只需将所有可能的值存储在一个数组中并迭代它并检查每个值是否合适.