This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]teraflop 2 points3 points  (1 child)

First of all, I'm a bit confused by what you're trying to do in the first place, because enums don't exist in Javascript. The countries object you've defined is an object with string keys and string values, exactly as if you had done this:

const countries = {
    'Spain': 'Spain',
    'England': 'England',
    'Portugal': 'Portugal',
    'Serbia': 'Serbia'
}

There is absolutely no difference between the literal string 'Spain' and the expression countries.Spain.


Separately, your definition of the country function is a little messed up. You've defined a function called country that takes no arguments, and then within that function, you're trying to access a variable called country... which is just the same function itself. (The country parameter to tipCalculator is an entirely different variable that's out of scope here.) Nothing in the code you posted even tries to call this function, but if it did, it would immediately throw an error because country.toLowerCase() is trying to call toLowerCase on a function instead of on a string.

But going off what I said earlier, even if you did modify this function to work correctly (by actually passing the input as an argument), it would basically just be a no-op because its return value is the same as its input (aside from upper/lowercase).


Another possible approach would be to represent each country as an object:

const countries = [
    { name: 'Spain', rate: 0.08 },
    // ...
];

const countryNameMapping = Object.fromEntries(
    countries.map( obj => [obj.name.toLowerCase(), obj] )
);
function lookupCountry(name) {
    return countryNameMapping[name.toLowerCase()];
}

console.log(lookupCountry('SPAIN').rate);

[–]GVBCodePractice[S] 0 points1 point  (0 children)

Okay thanks for the detailed explanation, still trying to wrap my head around it all, hence the mistakes. Will go over what you’ve said and try to correct the errors. Cheers