discount-calculator-js
Version:
A versatile utility for calculating various types of discounts
236 lines (195 loc) • 7.15 kB
JavaScript
const readline = require('readline');
const {
calculateDiscount,
getAvailableDiscountTypes
} = require('./index');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// ANSI color codes for better output
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
dim: '\x1b[2m',
underscore: '\x1b[4m',
blink: '\x1b[5m',
reverse: '\x1b[7m',
hidden: '\x1b[8m',
fg: {
black: '\x1b[30m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
white: '\x1b[37m'
},
bg: {
black: '\x1b[40m',
red: '\x1b[41m',
green: '\x1b[42m',
yellow: '\x1b[43m',
blue: '\x1b[44m',
magenta: '\x1b[45m',
cyan: '\x1b[46m',
white: '\x1b[47m'
}
};
// Display the welcome message
function displayWelcome() {
console.log(`
${colors.bright}${colors.fg.cyan}====================================${colors.reset}
${colors.bright}${colors.fg.cyan} DISCOUNT CALCULATOR ${colors.reset}
${colors.bright}${colors.fg.cyan}====================================${colors.reset}
Calculate various types of discounts quickly and easily.
`);
}
// Display available discount types
function displayDiscountTypes() {
const discountTypes = getAvailableDiscountTypes();
console.log(`${colors.bright}Available discount types:${colors.reset}\n`);
discountTypes.forEach((type, index) => {
console.log(`${colors.fg.green}${index + 1}. ${type.name}${colors.reset}`);
console.log(` ${colors.dim}${type.description}${colors.reset}\n`);
});
}
// Function to prompt for input
function prompt(question) {
return new Promise((resolve) => {
rl.question(question, (answer) => {
resolve(answer);
});
});
}
// Process percentage discount
async function processPercentageDiscount() {
const amountStr = await prompt(`${colors.fg.cyan}Enter the original amount: $${colors.reset}`);
const percentageStr = await prompt(`${colors.fg.cyan}Enter the discount percentage: ${colors.reset}`);
try {
const amount = parseFloat(amountStr);
const percentage = parseFloat(percentageStr);
const result = calculateDiscount(amount, {
type: 'percentage',
value: percentage,
formatOutput: true
});
console.log(`\n${colors.bright}${colors.fg.green}Calculation Result:${colors.reset}`);
console.log(result.formattedOutput);
} catch (error) {
console.error(`\n${colors.fg.red}Error: ${error.message}${colors.reset}\n`);
}
}
// Process fixed discount
async function processFixedDiscount() {
const amountStr = await prompt(`${colors.fg.cyan}Enter the original amount: $${colors.reset}`);
const discountStr = await prompt(`${colors.fg.cyan}Enter the fixed discount amount: $${colors.reset}`);
try {
const amount = parseFloat(amountStr);
const discount = parseFloat(discountStr);
const result = calculateDiscount(amount, {
type: 'fixed',
value: discount,
formatOutput: true
});
console.log(`\n${colors.bright}${colors.fg.green}Calculation Result:${colors.reset}`);
console.log(result.formattedOutput);
} catch (error) {
console.error(`\n${colors.fg.red}Error: ${error.message}${colors.reset}\n`);
}
}
// Process buy X get Y discount
async function processBuyXGetYDiscount() {
const amountStr = await prompt(`${colors.fg.cyan}Enter the price per item: $${colors.reset}`);
const quantityStr = await prompt(`${colors.fg.cyan}Enter the total number of items: ${colors.reset}`);
const buyQuantityStr = await prompt(`${colors.fg.cyan}Enter how many items to buy (X): ${colors.reset}`);
const getQuantityStr = await prompt(`${colors.fg.cyan}Enter how many items are free (Y): ${colors.reset}`);
try {
const amount = parseFloat(amountStr);
const quantity = parseInt(quantityStr);
const buyQuantity = parseInt(buyQuantityStr);
const getQuantity = parseInt(getQuantityStr);
const result = calculateDiscount(amount, {
type: 'buyxgety',
quantity,
buyQuantity,
getQuantity,
formatOutput: true
});
console.log(`\n${colors.bright}${colors.fg.green}Calculation Result:${colors.reset}`);
console.log(result.formattedOutput);
} catch (error) {
console.error(`\n${colors.fg.red}Error: ${error.message}${colors.reset}\n`);
}
}
// Process tiered discount
async function processTieredDiscount() {
const amountStr = await prompt(`${colors.fg.cyan}Enter the original amount: $${colors.reset}`);
console.log(`\n${colors.fg.yellow}Now let's set up the discount tiers:${colors.reset}`);
const tiers = [];
let addMore = true;
while (addMore) {
const thresholdStr = await prompt(`${colors.fg.cyan}Enter the minimum purchase amount for this tier: $${colors.reset}`);
const typeStr = await prompt(`${colors.fg.cyan}Enter discount type (percentage/fixed): ${colors.reset}`);
const discountStr = await prompt(`${colors.fg.cyan}Enter the discount ${typeStr === 'percentage' ? 'percentage' : 'amount'}: ${typeStr === 'percentage' ? '%' : '$'}${colors.reset}`);
tiers.push({
threshold: parseFloat(thresholdStr),
type: typeStr.toLowerCase(),
discount: parseFloat(discountStr)
});
const addMoreStr = await prompt(`\n${colors.fg.yellow}Add another tier? (y/n): ${colors.reset}`);
addMore = addMoreStr.toLowerCase() === 'y';
}
try {
const amount = parseFloat(amountStr);
const result = calculateDiscount(amount, {
type: 'tiered',
tiers,
formatOutput: true
});
console.log(`\n${colors.bright}${colors.fg.green}Calculation Result:${colors.reset}`);
console.log(result.formattedOutput);
} catch (error) {
console.error(`\n${colors.fg.red}Error: ${error.message}${colors.reset}\n`);
}
}
// Main function
async function main() {
displayWelcome();
let continueCalculating = true;
while (continueCalculating) {
displayDiscountTypes();
const typeChoice = await prompt(`${colors.fg.yellow}Select a discount type (1-4): ${colors.reset}`);
switch (typeChoice) {
case '1':
await processPercentageDiscount();
break;
case '2':
await processFixedDiscount();
break;
case '3':
await processBuyXGetYDiscount();
break;
case '4':
await processTieredDiscount();
break;
default:
console.log(`\n${colors.fg.red}Invalid choice. Please try again.${colors.reset}\n`);
continue;
}
const continueStr = await prompt(`\n${colors.fg.yellow}Calculate another discount? (y/n): ${colors.reset}`);
continueCalculating = continueStr.toLowerCase() === 'y';
if (continueCalculating) {
console.log('\n');
}
}
console.log(`\n${colors.fg.cyan}Thank you for using the Discount Calculator!${colors.reset}\n`);
rl.close();
}
// Start the program
main().catch(error => {
console.error(`\n${colors.fg.red}An unexpected error occurred: ${error.message}${colors.reset}\n`);
rl.close();
});