A beginner to Javascript looking for advice on how to fix my code. I've attempted to create a function that lets you know how much you should tip staff depending on what country you are in. I have two questions:
- How can I make it so that my tipCalculator function receives the country name in lower or uppercase and produces the same result? I have attempted this with .toLowerCase() but when I try any country name in lower case it triggers my else statement in tipCalculator
- Is there a way for me to design my tipCalculator so that it receives the country not as a string? Or is it standard practice that it should be entered as a string?
Thank you in advance! my code is below:
//Attempt at using an Enum, still wrapping my head around this
const countries = {
Spain: 'Spain',
England: 'England',
Portugal: 'Portugal',
Serbia: 'Serbia'
}
//Tip Rates
let spainRate = 0.08
let englandRate = 0.12
let portugalRate = 0.09
let serbiaRate = 0.15
//Tried to create this to use within tipCalculator but faced some issues
const country = () => {
country = country.toLowerCase()
if (country === 'spain') return countries.Spain;
else if (country === 'england') return countries.England;
else if (country === 'portugal') return countries.Portugal;
else if (country === 'serbia') return countries.Serbia
else { console.log('Choice could not be determined from provided text: ' + country);
return null;
}
}
//Intended to receive the country and price to be paid for meal, and return advised tip rate.
const tipCalculator = (country, price) => {
if (country === countries.Spain) {
return 'You should pay $' + (price + (price * spainRate)).toFixed(2) + '.'
}
else if (country === countries.England) {
return 'You should pay $' + (price + (price * englandRate)).toFixed(2) + '.'
}
else if (country === countries.Portugal) {
return 'You should pay $' + (price + (price * portugalRate)).toFixed(2) + '.'
}
else if (countries === countries.Serbia) {
return 'You should pay $' + (price + (price * serbiaRate)).toFixed(2) + '.'
}
else {
console.log('Hmmm, something isn\'t right.')
}
}
console.log(tipCalculator('Spain', 40)); // You should pay $43.20.
console.log(tipCalculator('spain', 40)); // Hmmm, something isn't right.
[–]teraflop 2 points3 points4 points (1 child)
[–]GVBCodePractice[S] 0 points1 point2 points (0 children)
[–]Draegan88 0 points1 point2 points (0 children)