通过命令行程序计算价格

时间:2018-08-04 13:48:29

标签: javascript node.js

我发现了一个非常有趣的练习,要求编写一个命令行程序,该程序计算订单的总价,其中:

1 。支付的总金额是每种产品的价格 sum ,其顺序为乘以数量订单中每个商品的数量

2 。 csv文件中的价格不包含增值税

3 。支付的总金额必须包含23%固定税率的增值税

4 。如果产品缺货,则程序必须以错误代码1结尾并显示一条消息。

有了这个,一个包含以下数据的csv文件:

P1,5,1000.00
P2,8,250.00
P3,15,125.00
P4,10,250.00
P5,2,2500.00

该程序必须从命令行运行,并带有以下参数:

示例: $ CalculateOrder Catalog.txt P4 6 P10 5 P12 1

总计:4151,25

这是我目前所拥有的:

var program = require('commander');
const csv = require('csv');
const fs = require('fs');

program
    .version('1.0.0')
    .option('-l, --list [list]', 'list of order prices in sample.catalog.csv')
    .parse(process.argv)

console.log("hello world")
console.log("list of order prices", program.list);

/* 
    To read csv file and print the data to the console:
    [node orderPrice --list input/sample.catalog.csv]
*/

let parse = csv.parse;
let stream = fs.createReadStream(program.list)
    .pipe(parse({ delimiter: ',' }));

stream
    .on('data', function (data) {
        let product = data[0];
        let quantity = data[1];
        let price = data[2];
        console.log(product, quantity, price);
    });

通过命令行,我可以看到csv文件中的所有数据,但是除了计算价格所需的javascript函数外,我不知道下一步该怎么做。

我是node.js新手,感谢您的帮助。 谢谢!

1 个答案:

答案 0 :(得分:1)

  

要支付的总金额是订单中每种产品的价格乘以订单中每种产品的数量之和

首先需要一个全局变量来计算总数:

 var total = 0;

每当有新行到达时,计算价格并将其添加到总计中:

 total += price * quantity;

然后,当流完成时,只需记录总数:

 stream.on("finish", function() {
   console.log("Total price:", total);
 });
  

要支付的总金额必须包含23%固定税率的增值税

那只是最后的一些乘法。

  

如果产品缺货,则程序必须以错误代码1结尾并显示一条消息。

在这种情况下,您应该破坏流:

   if(quantity > 20) {
     stream.destroy(new Error("Quantity exceeds stored amounts"));
   }

然后,您可以侦听流中的错误并采取相应措施:

  stream.on("error", function(error) {
    console.error("The following error occured:", error);
  });

通过这种方式,“完成”事件将不会被触发,并且不会显示总数。