[Codewars] JS : Highest and Lowest

theSummerSolstice·2020년 7월 6일
0

Codewars를 하루에 한 문제씩 풀기 시작한지 딱 이주일 정도가 지난 것 같다. 여전히 어렵고, 여전히 허접한 코드이지만 조금씩 다른 사람들의 풀이 방식과 패턴이 비슷해지는 것 같기도 하다. (하지만 진짜 내 코드 너무 부끄러워☹️) 그래도 앞으로 나아질테니 용기내서 올려본다.

Question

In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.

Examples

highAndLow("1 2 3 4 5"); // return "5 1"
highAndLow("1 2 -3 4 5"); // return "5 -3"
highAndLow("1 9 3 4 -5"); // return "9 -5"

Notes

  • All numbers are valid Int32, no need to validate them.
  • There will always be at least one number in the input string.
  • Output string must be two numbers separated by a single space, and highest number is first.

My answer

function highAndLow(numbers){
  const turnNumber = numbers.split(" ").map(item => Number(item));
  const max = Math.max.apply(null, turnNumber);
  const min = Math.min.apply(null, turnNumber);
  
  const arr = [];
  arr.push(max, min);
  return arr.join(" ");
}
  1. Math.max / Math.min 함수를 apply 사용해서 배열 값을 넘겼다.
  2. map의 경우, 내 코드처럼 쓰지 않고 map(Number)만 사용해도 동일한 결과가 나온다. (콜백함수)
  3. 최대값과 최소값을 추출 후, 배열에 넣고 join을 통해 문자열로 변경했는데 다음엔 아래처럼 간결하게 쓰자.
return max + ' ' + min;

0개의 댓글