Created
February 26, 2016 08:54
-
-
Save prashcr/de90d877d3674d5f4822 to your computer and use it in GitHub Desktop.
First Code Academy exercise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const readline = require('readline') | |
const prices = { | |
MAX: 1000, | |
MAC: 1500, | |
MAE: 2000, | |
MAL: 3000, | |
TAX: 2700, | |
TAC: 3900, | |
TAE: 5100 | |
} | |
const specials = { | |
MAX: 1000, // quantity >= 2 | |
MAC: 1500, // quantity >= 3 | |
MAE: 2000, // quantity >= 2 | |
MAL: 2500 // Also bought MA[XCE] | |
} | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}) | |
rl.question( | |
`Please enter your order as <quantity><duration><code> separated by commas | |
E.g. 3MAX, 4MAE, 2TAC | |
> `, | |
handleOrder) | |
function handleOrder(answer) { | |
const items = answer.split(',').map(s => s.trim()) | |
const total = items.reduce((total, item) => { | |
return total + calculatePrice(item, items) | |
}, 0) | |
console.log(`The total price is HKD ${total}`) | |
console.log('Thank you for choosing First Code Academy') | |
rl.close() | |
} | |
function calculatePrice(item, items) { | |
const quantity = +item.substr(0, 1) | |
const code = item.substr(1) | |
if (code === 'MAX') { | |
return Math.floor(quantity / 2) * specials[code] + quantity % 2 * prices[code] | |
} | |
if (code === 'MAC') { | |
return Math.floor(quantity / 3) * specials[code] + quantity % 3 * prices[code] | |
} | |
if (code === 'MAE') { | |
return Math.floor(quantity / 2) * specials[code] + quantity % 2 * prices[code] | |
} | |
// String.match returns either null or non-empty array | |
// so we can implicitly coerce it to a boolean | |
if (code === 'MAL' && items.some(item => item.match(/MA[XCE]/))) { | |
return quantity * specials[code] | |
} | |
return quantity * prices[code] | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment