function solution(lottos, win_nums) {
let answer = [];
let max = 0;
let min = 0;
const LOTTO_LEN = 6;
for (let i = 0; i < LOTTO_LEN; i++) {
if (win_nums.includes(lottos[i])) min++;
if (lottos[i] === 0) max++;
}
max += min;
const stLen = LOTTO_LEN + 1; // 7
answer.push(
max === 0 ? stLen - 1 : stLen - max,
min === 0 ? stLen - 1 : stLen - min
);
return answer;
}
처음에 푼 코드는 답은 나왔지만 약간 정신이 없어서 코드를 개선해보기로 했다.
우선 for-i문은 순서가 중요하지 않은 로직이기 때문에 for-of로 축소하려다가 생각해보니 조건에 일치하는 값을 찾는 것이라 filter로 바꿔주었다.
for문 끝나고 어정쩡하게 있던 max += min
라인은 max 뒤에 min을 더해줘서 생략했다.
function solution(lottos, win_nums) {
let answer = [];
let max = 0;
let min = 0;
const LOTTO_LEN = 6;
min = lottos.filter((lotto) => win_nums.includes(lotto)).length;
max = lottos.filter((lotto) => !lotto).length + min;
const stLen = LOTTO_LEN + 1; // 7
answer.push(
max === 0 ? stLen - 1 : stLen - max,
min === 0 ? stLen - 1 : stLen - min
);
return answer;
}
=== 0
부분을 !
로 줄이니 눈에 들어오는 코드가 간결해져서 더 축소할 수 있는 부분이 보였다.function solution(lottos, win_nums) {
let answer = [];
let max = 0;
let min = 0;
const LOTTO_LEN = 6;
min = lottos.filter((lotto) => win_nums.includes(lotto)).length;
max = lottos.filter((lotto) => !lotto).length + min;
const stLen = LOTTO_LEN + 1; // 7
answer.push(
stLen - (!max ? 1 : max),
stLen - (!min ? 1 : min),
);
return answer;
}
function solution(lottos, win_nums) {
let answer = [];
let min = lottos.filter((lotto) => win_nums.includes(lotto)).length;
let max = lottos.filter((lotto) => !lotto).length + min;
const STANDARD_LEN = lottos.length + 1;
answer.push(
STANDARD_LEN - (!max ? 1 : max),
STANDARD_LEN - (!min ? 1 : min),
);
return answer;
}
총 22줄을 13줄로 줄이는 데 성공
선언한 변수들을 answer.push에 모두 때려넣으면 이것보다 더 줄일 수 있겠지만 가독성을 위해서 여기까지만 진행했다.
function solution(lottos, win_nums) {
const rank = [6, 6, 5, 4, 3, 2, 1];
let minCount = lottos.filter(v => win_nums.includes(v)).length;
let zeroCount = lottos.filter(v => !v).length;
const maxCount = minCount + zeroCount;
return [rank[maxCount], rank[minCount]];
}