본문 바로가기
알고리즘/Codewars

[Codewars] Basic Mathematical Operations (8 kyu) / JavaScript

by fluss 2022. 12. 26.

https://www.codewars.com/kata/57356c55867b9b7a60000bd7

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

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
 

설명:

네가지 기본적인 수학 연산을 하는 함수를 만드세요.

 

함수는 세가지 인수 - operation(문자열/문자), value1(숫자), value2(숫자)를 받아야합니다.

함수는 선택된 연산을 적용한 결과를 반환해야 합니다.

 

예시(Operator, value1, value2) --> 출력

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

풀이

조건문으로 입력받은 연산자의 경우에 따라 계산을 하고 그 값을 반환하였다.

 

코드

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

댓글