CodeWars 코딩 문제 2021/05/27 - Turn String Input into Hash

이호현·2021년 5월 27일
0

Algorithm

목록 보기
121/138

[문제]

Please write a function that will take a string as input and return a hash. The string will be formatted as such. The key will always be a symbol and the value will always be an integer.

"a=1, b=2, c=3, d=4"

This string should return a hash that looks like

{ 'a': 1, 'b': 2, 'c': 3, 'd': 4}

(요약) 주어진 문자열을 객체로 만들어라.

[풀이]

function strToHash(str){
  if(!str.length) return {};

  const answer = {};

  str.split(', ').forEach(str => {
    const temp = str.split('=');
    answer[temp[0]] = temp[1]|0;
  })
 
  return answer;
}

적당히 split()을 이용해 원하는 형식에 맞게 만들어주면 됨.

profile
평생 개발자로 살고싶습니다

0개의 댓글