我在Sonar中面临一个重复的问题,我无法弄清楚如何纠正它。
这是示例代码。请不要通过formFields是我的项目中保持不变状态。因此,如果我做 public static void main(String[] args) {
Scanner in = new Scanner(System.in);
...
// sameElements method requires 2 inputs: int[]-array 'a' and int[]-array 'b'
// OLD: System.out.println("These are " + sameElements(result1));
// NEW: May not necessarily be correct but it compiles.
System.out.println("These are " + sameElements(a, b));
}
/**
* Comparing for equality by sum is going to give bad results
* i.e sum1 = 10 - elements [1, 5, 4] Is not equal to
* sum2 = 10 - elements [0, 6, 4]
*/
public static boolean sameElements(int[] a, int[] b) {
int sum = 0;
int sum1 = 0;
int sum2 = 0;
for (int num : a) {
// this will cumulatively total int[]-array 'a' into 'sum1'. 'sum' is never updated.
sum1 = sum + num;
// shorthand for this is sum2 += num
}
for (int num : b) {
// this will cumulatively total int[]-array 'b' into 'sum2'. 'sum' is never updated.
sum2 = sum + num;
// shorthand for this is sum2 += num
}
int result = sum1 - sum2; // 'sum' never used.
return result == 0;
}
,在这种情况下,我试图获取特定字段formFields.getIn(['home', 'value'])
的值。我将所有值与home
进行比较。并且一旦我进行比较,便将其各自的字符串推入'true'
中。这些行(3,4和5,6)显示tat我正在复制比较并将数据推入数组。
lifeEvents
为了避免重复,我尝试了以下方法
1. export const getLifeEvents = formFields => {
2. const lifeEvents = [];
3. if(formFields.getIn(['home', 'value']) === 'true')
4. lifeEvents.push("Buy home");
5. if(formFields.getIn(['married', 'value']) === 'true')
6. lifeEvents.push("Getting married");
7. return lifeEvents;
8. }
当我这样做时,我总是变得不确定。有人可以建议吗
答案 0 :(得分:2)
使用键和文本创建一个对象。用reduce循环遍历
const myEvents = {
home: 'Buy home',
married: 'Getting married'
};
export const getLifeEvents = formFields => {
return Object.entries(myEvents).reduce((lifeEvents, [key, text]) => {
if (formFields.getIn([key, 'value']) === 'true') {
lifeEvents.push(text);
}
return lifeEvents;
}, []);
}