Basic Mathematical Operations

chris0205.eth·2022년 2월 27일
0

Codewars

목록 보기
4/5
post-thumbnail

Prob

Your task is to create a function that does four basic mathematical operations.

The function should take three arguments - operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying the chosen operation.

Examples(Operator, value1, value2) --> output

('+', 4, 7) --> 11
('-', 15, 18) --> -3
('*', 5, 5) --> 25
('/', 49, 7) --> 7

Answ

my

function basicOp(operation, value1, value2){
  if (operation=="+"){
    return value1 + value2;
  }
  if (operation=="-"){
    return value1 - value2;
  }
  if (operation=="*"){
    return value1 * value2;
  }
  if (operation=="/"){
    return value1 / value2;
  }
}

연산자가 문자열로 input 되기 때문에 value1,value2에 바로 적용시킬 수 없다.
따라서 if 조건문을 사용했다.

others_1

function basicOp(operation, value1, value2) {
    switch (operation) {
        case '+':
            return value1 + value2;
        case '-':
            return value1 - value2;
        case '*':
            return value1 * value2;
        case '/':
            return value1 / value2;
        default:
            return 0;
    }
}

switch 문은 case와 switch의 parameter가 일치하면 다음을 실행한다.
default 값은 모든 case가 일치하지 않을 때 실행된다.

others_2

function basicOp(operation, value1, value2){
  return eval(value1 + operation + value2);
}

eval 메소드는 문자열로 표현된 연산을 실제 연산으로 바꾸어서 해준다.
하지만, eval은 그리 효율적이고 간편한 연산을 해주는 함수가 아니므로 되도록이면 사용을 지양하자!


마치며

switch문에 대해서 새롭게 알게 되었고, eval()이라는 메소드도 알았지만 주의할 점이 많고 까다로운 메소드라는 것 또한 알았다.

profile
long life, long goal

0개의 댓글