问题描述
我现在有一个非常好的案例。 我有一个依赖于 2 个变量的函数,我需要实现这个函数的代码才能按照给定的期望表正确响应
const cases = [
[1,1,false],[1,2,true],3,4,5,6,[2,];
// not relevant but fyi as code is js used jest testeach to check all of cases outputs
test.each(
cases,function(nr1,nr2,expected) {
expect(isInGroup(nr1,nr2)).toBe(expected);
},);
以上是格式[firstNr: int,secondNr: int,expectedFunctionOutput: bool]
函数签名如下
export function isInGroup(firstNr,secondNr) {
// Todo implement
// return correct stuff
}
PS:案例的分布确保变量 1 和变量 2 在它们存在的所有案例中都有 50% true
案例。
我最初尝试将它们分组分发,但没有成功,仅从提供的测试用例中覆盖了 75% 的测试用例。
export function isInGroup(firstNr,secondNr) {
return (
(firstNr % 2 === 0 && secondNr % 2 === 0) ||
(firstNr % 2 !== 0 && secondNr % 2 === 0) ||
(firstNr % 2 === 0 && secondNr % 2 !== 0)
);
}
此外,由于值是数字而不是布尔值,因此不能使用布尔表直接找到公式
解决方法
我自己解决了这个问题。
这个函数给出了想要的结果:
return firstNr % 2 !== 0 ? secondNr % 2 === 0 : secondNr % 2 !== 0;