문제
풀이 1
function solution(dartResult) {
let bonus = ['_','S','D','T']
let score = dartResult.match(/\d{1,}(?=['S','D','T'])/gi)
let bonusScore = dartResult.match(/['s','d','t']/gi)
let optionCheck = -1
let option = [0,0,0]
bonusScore.map((v,i) => {
score[i] = score[i] ** bonus.indexOf(bonusScore[i])
})
dartResult.split('').map((v,j) => {
if (dartResult[j] === 'S' || dartResult[j] === 'D' || dartResult[j] === 'T') optionCheck++
if (dartResult[j] ==='*' || dartResult[j] ==='#') {
option[optionCheck] = dartResult[j]
}
})
option.map((v,k) => {
if (option[k] === '#'){
score[k] = -score[k]
}
else if (option[k] === '*') {
if (k>0) score[k-1] = score[k-1] * 2
score[k] = score[k] * 2
}
})
return (score.reduce((a,b) => a+b))
}
풀이 2
function solution(dartResult) {
const bonus = { 'S': 1, 'D': 2, 'T': 3 },
options = { '*': 2, '#': -1, undefined: 1 };
let darts = dartResult.match(/\d.?\D/g);
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]];
if (split[3] === '*' && darts[i - 1]) darts[i - 1] *= options['*'];
darts[i] = score;
}
return darts.reduce((a, b) => a + b);
}