Programmers, 다항식 더하기

# Level 0. 다항식 더하기

다항식 더하기

문제 설명

한 개 이상의 항의 합으로 이루어진 식을 다항식이라고 합니다. 다항식을 계산할 때는 동류항끼리 계산해 정리합니다. 덧셈으로 이루어진 다항식 polynomial이 매개변수로 주어질 때, 동류항끼리 더한 결괏값을 문자열로 return 하도록 solution 함수를 완성해보세요. 같은 식이라면 가장 짧은 수식을 return 합니다.

제한사항

문제풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function solution(polynomial) {
  const answer = [0, 0];
  const splitted = polynomial.split(" + ");

  if (splitted.length === 1) return polynomial;

  splitted.forEach((term) => {
    if (term[term.length - 1] !== "x") {
      answer[1] += term * 1;
      return;
    }

    answer[0] += term === "x" ? 1 : term.slice(0, term.length - 1) * 1;
  });

  if (answer[0] === 1) answer[0] = "";
  answer[0] += "x";
  if (answer[0] === "0x") answer.shift();
  if (answer[1] === 0) answer.pop();

  return answer.join(" + ");
}

리팩토링

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const filterPolynomial = (polynomialStr) => {
  const validTerm = new RegExp("[0-9]*x|[0-9]+", "g");
  return polynomialStr.match(validTerm);
};

const getPolynomialResult = (polynomialArr) => {
  const result = [0, 0];
  polynomialArr.forEach((term) => {
    if (term[term.length - 1] !== "x") {
      result[1] += parseInt(term);
      return;
    }

    result[0] += term === "x" ? 1 : parseInt(term);
  });

  return result;
};

const formatPolynomial = (xNumber, constant) => {
  if (!xNumber) return [constant];

  const result = [];
  xNumber === 1 ? result.push("x") : result.push(`${xNumber}x`);
  if (constant) result.push(constant);

  return result;
};

function solution(polynomial) {
  const filtered = filterPolynomial(polynomial);
  const [x, constant] = getPolynomialResult(filtered);
  const answer = formatPolynomial(x, constant);

  return answer.join(" + ");
}

두번째 리팩토링

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function solution(polynomial) {
  const answer = [0, 0];
  const splitted = polynomial.split(" + ");

  if (splitted.length === 1) return polynomial;

  splitted.forEach((term) => {
    let index = 0;
    if (term[term.length - 1] !== "x") index = 1;

    answer[index] += term === "x" ? 1 : parseInt(term);
  });

  if (!answer[0]) return `${answer[1]}`;
  if (!answer[1]) answer.pop();
  answer[0] === 1 ? (answer[0] = "x") : (answer[0] += "x");

  return answer.join(" + ");
}