DEV Community

loading...

Discussion on: Daily Challenge #56 - Coffee Shop

Collapse
ynndvn profile image
La blatte

Well, here it is:

const pay = (amount) => {
  const beverage = {2.2:'Americano',2.3:'Latte',2.4:'Flat white',3.5:'Filter'}[amount];
  return beverage ? `Here is your ${beverage}, have a nice day!`:'Sorry, exact change only, try again tomorrow!';
}

Which outputs:

pay(2.2)
"Here is your Americano, have a nice day!"
pay(2.3)
"Here is your Latte, have a nice day!"
pay(2.30)
"Here is your Latte, have a nice day!"
pay(2.31)
"Sorry, exact change only, try again tomorrow!"
Collapse
smz_68 profile image
Ardalan

I like it

Collapse
kvharish profile image
K.V.Harish

Good approach. What if the function is called like

pay('2.20')
Collapse
georgecoldham profile image
George

What is the name for the

{a:'A', b:'B', c:'C'}[value]

notation? I seem to have managed to avoid seeing this for years!

Collapse
aayzio profile image
aayzio • Edited

The {} operator would define a map. In the solution that would be a map of float type keys for string type values. The [ ] is then used to access a particular key.

Thread Thread
georgecoldham profile image
George

Awesome, thank you!

Thread Thread
aayzio profile image
aayzio

You're welcome!

Collapse
skiilaa profile image
skiilaa

Here is it smaller :)

(a,b={2.2:'Americano',2.3:'Latte',2.4:'Flat white',3.5:'Filter'}[a])=>b?`Here is your ${b}, have a nice day!`:`Sorry, exact change only, try again tomorrow!`
Collapse
lordapple profile image
LordApple • Edited

I also like it, and decided to rewrite it in c++

    const auto pay = [](float cash){
        const auto coffee = std::unordered_map<float, std::string>{
                {2.2, "Americano"},
                {2.3, "Latte"},
                {2.4, "Flat white"},
                {3.5, "Filter"},

        }[cash];

        return coffee.empty() ? "Sorry, exact change only, try again tomorrow!"
                              : "Here is your " + coffee + ", have a nice day!";
    };