I need to do shopping list with node that asks the user the product and the price. Then it needs to show the most expensive and cheapest product. I know how to get the price and the cheapest and most expensive values, but can't seem to figure out how I can add the product and price together.
Here is basically the raw version I have:
let array = [];
const mainfunc = () => {
rl.question("add price : ", (aa) => {
array.push(aa);
console.log("---");
console.log("Product " aa " added");
console.log("added products " array);
console.log("Most expensive " Math.max(...array));
console.log("Cheapest " Math.min(...array));
console.log("---");
mainfunc();
});
};
mainfunc();
This is basically what I want the program to ask and give simplified:
Give product 1: Banana
Give price: 1
Give product 2: Apple
Give price: 2
Give product 3: Pear
Give price: 3
Most expensive item: Pear 3
Cheapest item: Banana 1
It only needs to work on node.js command line and it doesn't have to be fancy. I'm just stuck with it.
CodePudding user response:
You can store product and price in an array of objects.
For example:
const productPrices = []
productPrices.push({
productName: "ABC",
price: 20
})
productPrices.push({
productName: "XYZ",
price: 30
})
// Find product having max price
productPrices[productPrices.indexOf(Math.max(...productPrices(p => p.price)))]
// Find product having cheapest price
productPrices[productPrices.indexOf(Math.min(...productPrices(p => p.price)))]
CodePudding user response:
const util = require('util');
const readline = require('readline');
const cli = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const question = util.promisify(cli.question).bind(cli);
const PRODUCTS_COUNT = 4;
const productQuestions = ['Give product', 'Give price: '];
const answers = [];
let tmp = {};
const questions = [...Array(PRODUCTS_COUNT * 2)]
.map((_, index) => index % 2 ? productQuestions[1] : `${productQuestions[0]} ${index / 2 1}: `)
.map((item, index) => () => new Promise(async (resolve, reject) => {
try {
const answer = await question(item);
if ( index % 2 ) {
tmp.price = Number(answer);
answers.push(tmp);
tmp = {};
} else {
tmp.product = answer;
}
resolve();
} catch {
reject();
}
}));
(async () => {
for ( const question of questions ) {
await question();
}
console.log(answers);
process.exit(0);
})();