curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5ecd.md
Given an amount of money you have, and an array of items you want to buy, determine how many of them you can afford.
["Amount", "Currency Code"]. For example: ["150.00", "USD"] or ["6000", "JPY"].Use the following exchange rates to convert values:
| Currency | 1 Unit Equals |
|---|---|
| USD | 1.00 USD |
| EUR | 1.10 USD |
| GBP | 1.25 USD |
| JPY | 0.0070 USD |
| CAD | 0.75 USD |
"Buy them all!"."Buy the first X items.", where X is the number of items you can afford when purchased in the order given.buyItems(["150.00", "USD"], [["50.00", "USD"], ["75.00", "USD"], ["30.00", "USD"]]) should return "Buy the first 2 items.".
assert.equal(buyItems(["150.00", "USD"], [["50.00", "USD"], ["75.00", "USD"], ["30.00", "USD"]]), "Buy the first 2 items.");
buyItems(["200.00", "EUR"], [["50.00", "USD"], ["50.00", "USD"]]) should return "Buy them all!".
assert.equal(buyItems(["200.00", "EUR"], [["50.00", "USD"], ["50.00", "USD"]]), "Buy them all!");
buyItems(["100.00", "CAD"], [["20.00", "USD"], ["15.00", "EUR"], ["10.00", "GBP"], ["6000", "JPY"], ["5.00", "CAD"], ["10.00", "USD"]]) should return "Buy the first 3 items.".
assert.equal(buyItems(["100.00", "CAD"], [["20.00", "USD"], ["15.00", "EUR"], ["10.00", "GBP"], ["6000", "JPY"], ["5.00", "CAD"], ["10.00", "USD"]]), "Buy the first 3 items.");
buyItems(["5000", "JPY"], [["3.00", "USD"], ["1000", "JPY"], ["5.00", "CAD"], ["2.00", "EUR"], ["4.00", "USD"], ["2000", "JPY"]]) should return "Buy them all!".
assert.equal(buyItems(["5000", "JPY"], [["3.00", "USD"], ["1000", "JPY"], ["5.00", "CAD"], ["2.00", "EUR"], ["4.00", "USD"], ["2000", "JPY"]]), "Buy them all!");
buyItems(["200.00", "USD"], [["50.00", "USD"], ["40.00", "EUR"], ["30.00", "GBP"], ["5000", "JPY"], ["25.00", "CAD"], ["20.00", "USD"]]) should return "Buy the first 5 items.".
assert.equal(buyItems(["200.00", "USD"], [["50.00", "USD"], ["40.00", "EUR"], ["30.00", "GBP"], ["5000", "JPY"], ["25.00", "CAD"], ["20.00", "USD"]]), "Buy the first 5 items.");
function buyItems(funds, items) {
return funds;
}
function buyItems(funds, items) {
const rates = {
USD: 1.00,
EUR: 1.10,
GBP: 1.25,
JPY: 0.0070,
CAD: 0.75
};
const [amount, currency] = funds;
let money = parseFloat(amount) * rates[currency];
for (let i = 0; i < items.length; i++) {
const [itemAmount, itemCurrency] = items[i];
const itemCostUSD = parseFloat(itemAmount) * rates[itemCurrency];
if (itemCostUSD > money) {
return `Buy the first ${i} items.`;
}
money -= itemCostUSD;
}
return "Buy them all!";
}