본문 바로가기
Research/Good codes

수 조작하기 reduce + function dict

by RIEM 2023. 11. 16.

좋다고 생각한 코드.

const operations = {
  w: (n) => n + 1,
  s: (n) => n - 1,
  d: (n) => n + 10,
  a: (n) => n - 10,
};

function solution(n, control) {
  return [...control].reduce((prev, op) => operations[op](prev), n);
}

딕셔너리 값에 함수를 넣어두고, 키를 리듀스의 curValue를 매개변수로 호출하는 것이 세련된 방식이라 생각

'Research > Good codes' 카테고리의 다른 글

Refactoring_01.리팩터링 기본  (0) 2023.09.27
Refactoring 2판) 01.리팩터링 기본  (0) 2023.08.29

댓글