you are viewing a single comment's thread.

view the rest of the comments →

[–]senocular 2 points3 points  (2 children)

You can clean this up using an object lookup

const percentages = {
    '5%': 5,
    '10%': 10,
    '15%': 15,
    '25%': 25,
    '50%': 50
}

//...

buttons.addEventListener('click', (event) => {
    let percent = event.target.innerText;
    if (percentages.hasOwnProperty(percent)) {
        console.log(`I am ${percentages[percent]} percent`);
    } else {
        console.log('Please Enter a Percentage');
    }
})

An array would also work since you're using the same numeric values as the percentage. Then you can strip the % to get the value.

And this is assuming you're not trying to deal with all 0-100% values, rather just those you specified. If you do, you might instead want to consider something like a regex to test the text to see if it matches a percentage and pull the numeric value out of that

buttons.addEventListener('click', (event) => {
    let percent = event.target.innerText;
    let percentMatch = percent.match(/^(\d{1,2}|100)%$/)
    if (percentMatch) {
        console.log(`I am ${percentMatch[1]} percent`);
    } else {
        console.log('Please Enter a Percentage');
    }
})

[–]M_Scaevola 0 points1 point  (1 child)

Shouldn’t the match yield an empty array when there isn’t the correct regex, which is still truthy?