dartResult를 점수별로 구분해서 풀었따.
const result
[ '1S', '2D*', '3T' ]
이런식으로 나오게!
/(\d+[SDT])([*#]?)/g
정규식을 이용했다.
function solution(dartResult) {
let answer=[]
const pattern = /(\d+[SDT])([*#]?)/g;
const result = dartResult.match(pattern);
//[ '1S', '2D*', '3T' ]
for(let i=0;i<3;i++){
const num= parseInt(result[i]) //1
const bonus = result[i].replace(num, ''); //'S' 또는 'S*'
if(bonus.includes('S')){ //점수계산
answer.push(Math.pow(num, 1))
}else if(bonus.includes('D')){
answer.push(Math.pow(num, 2))
}else{//'T'
answer.push(Math.pow(num, 3))
}
if(bonus.includes('*')||bonus.includes('#')){
if( bonus.includes('*')){
answer[i-1]=answer[i-1]*2
answer[i]=answer[i]*2
}else{
answer[answer.length-1]=answer[answer.length-1]*(-1)
}
}
}
return answer.reduce((a,c)=>a+c,0)
}
function solution(dartResult) {
const bonus = { 'S': 1, 'D': 2, 'T': 3 },
options = { '*': 2, '#': -1, undefined: 1 };
let darts = dartResult.match(/\d.?\D/g);
console.log(darts) // [ '1S', '2D*', '3T' ]
for (let i = 0; i < darts.length; i++) {
let split = darts[i].match(/(^\d{1,})(S|D|T)(\*|#)?/),
score =
Math.pow(split[1], bonus[split[2]]) * options[split[3]]
//console.log(split)
//[ '1S', '1', 'S', undefined, index: 0,
//input: '1S', groups: undefined ]
if (split[3] === '*' && darts[i - 1])
darts[i - 1] *= options['*'];
darts[i] = score;
}
return darts.reduce((a, b) => a + b);
}