function solution(numbers, hand) {
let answer = '';
let rightHandPosition = '#';
let leftHandPosition = '*';
for(let i = 0; i < numbers.length; i++) {
const checkHandle = checkPosition(numbers[i])
if(checkHandle){
answer += checkHandle
if(checkHandle === 'L'){
leftHandPosition = numbers[i]
}
if(checkHandle === 'R'){
rightHandPosition = numbers[i]
}
} else {
const findResult = findCenterPosition(numbers[i],leftHandPosition,rightHandPosition,hand)
answer += findResult.hand
if(findResult.hand === 'R'){
rightHandPosition = findResult.lastPosition
}
if(findResult.hand === 'L'){
leftHandPosition = findResult.lastPosition
}
}
}
return answer;
}
const checkPosition = (position) => {
switch(position){
case 1:
case 4:
case 7:
return 'L'
case 3:
case 6:
case 9:
return 'R'
default:
return false
}
}
const findCenterPosition = (number,left,right,hand) => {
const keyPad = [[1,4,7,'*'],[2,5,8,0],[3,6,9,'#']]
let leftIndex = keyPad[0].findIndex(item => item === left)
let rightIndex = keyPad[2].findIndex(item => item === right)
let centerIndex = keyPad[1].findIndex(item => item === number)
let result
let leftPosition = 0
let rightPosition = 0;
if(0 < leftIndex){
leftPosition = difference(centerIndex,leftIndex) + 1
} else {
leftPosition = difference(centerIndex, keyPad[1].findIndex(item => item === left))
}
if(0 < rightIndex){
rightPosition = difference(centerIndex,rightIndex) + 1
} else {
rightPosition = difference(centerIndex, keyPad[1].findIndex(item => item === right))
}
if(leftPosition === rightPosition){
if(hand === 'right'){
result= {
hand: 'R',
lastPosition: number
}
} else {
result ={
hand: 'L',
lastPosition: number,
}
}
} else {
if(leftPosition < rightPosition){
result = {
hand: 'L',
lastPosition: number
}
} else {
result = {
hand: 'R',
lastPosition: number
}
}
}
return result
}
function difference(a, b) {
return Math.abs(a - b);
}
Comment