DEV Community

Discussion on: Daily Challenge #8 - Scrabble Word Calculator

Collapse
 
jckuhl profile image
Jonathan Kuhl

A few days late, but here's my JavaScript solution, using reduce.

function scoreWord(string) {
    let word = string.toLowerCase();

    const scores = {
        a: 1,
        // ... etc, cut for conciseness
        z: 10,
        q: 10
    }

    let multiplier = 1;

    if(word.substring(word.length - 1) === '2') {
        multiplier = 2;
        word = word.substring(0, word.length - 1);
    } else if(word.substring(word.length - 1) === '3') {
        multiplier = 3;
        word = word.substring(0, word.length - 1);
    }

    let bonus = word.split('').filter(char => {
        return !['*', '^'].includes(char);
    }).length >= 7 ? 50 : 0;

    return word.split('').reduce((score, letter, index, letters) => {
        const next = index + 1 < letters.length ? letters[index + 1] : null;
        if('abcdefghijklmnopqrstuvwxyz'.includes(letter)) {
            if(next && ['*', '^'].includes(next)) {
                if(next === '^') {
                    return score += 0;
                }
                if(next === '*') {
                    if(index + 2 < letters.length && letters[index + 2] === '*') {
                        score += (scores[letter] * 3);
                    } else {
                        score += (scores[letter] * 2);
                    }
                    return score;
                }
            }
            return score += scores[letter];
        } else {
            return score;
        }
    }, 0) * multiplier + bonus;
}

I changed the rules a bit, since it's hard to distinguish between double/triple words and words that naturally end in d or t, I decided to use 2 or 3 instead.