[英]Count repeated numbers in array and return true (Cognitive Complexity)
I need to check if a number repeats itself at least three times in an array.我需要检查一个数字是否在数组中至少重复三次。 How can I refactor it to decrease the Cognitive Complexity that Lint keeps complaining about.
我如何重构它以降低 Lint 一直抱怨的认知复杂性。
Heres my code:这是我的代码:
let array11 = [1, 3, 2, 3, 5, 6, 7, 8, 9, 0, 1];
function checkDuplicateNumber (array11) {
for (let i = 0; i < array11.length; i += 1) {
let sameNumberLoop = 0;
for (let i2 = i; i2 < array11.length; i2 += 1) {
if (array11[i] === array11[i2]) {
sameNumberLoop += 1;
if (sameNumberLoop >= 3) {
return true;
}
}
}
}
}
Instead of iterating multiple times, iterate just once, while counting up the number of occurrences in an object or Map:与其迭代多次,不如只迭代一次,同时计算 object 或 Map 中出现的次数:
let array11 = [1, 3, 2, 3, 5, 6, 7, 8, 9, 0, 1]; function checkDuplicateNumber (array) { const counts = {}; for (const num of array) { counts[num] = (counts[num] || 0) + 1; if (counts[num] === 3) return true; } return false; }; console.log(checkDuplicateNumber(array11)); console.log(checkDuplicateNumber([3, 1, 3, 5, 3]));
let array11 = [1, 3, 2, 3, 5, 6, 7, 8, 9, 0, 1] let array22 = [1, 3, 2, 3, 5, 6, 7, 1, 9, 0, 1] function checkDuplicateNumber(arr) { const map = new Map() return arr.some((v) => (map.has(v)? (++map.get(v).count === 3): (map.set(v, { count: 1 }), false))) } console.log(checkDuplicateNumber(array11)) console.log(checkDuplicateNumber(array22))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.