本篇文章主要介绍了"JavaScript之POS机面向对象的设计",主要涉及到方面的内容,对于web前端感兴趣的同学可以参考一下:
前情提要商店里进行购物结算时会使用收银机(POS)系统,这台收银机会在结算时根据客户的购物车(Cart)中的商品(Item)和商店正在进行的优惠活动(Promo...
Order.prototype.initiate = function (items, promotions, list) {
_(list).each(function (raw_barcode) {
barcode = raw_barcode.substring(0,10);
var item = this.items[barcode] || _(items).findWhere({barcode: barcode});
this.original += item.addCount(raw_barcode);
this.items[barcode] = item;
}, this);
var two_with_one_list = _(promotions).findWhere({type: 'BUY_TWO_GET_ONE_FREE'}).barcodes;
_(two_with_one_list).each(function (barcode) {
this.items[barcode] && this.items[barcode].getPromotion();
}, this);
this.total = _(this.items).reduce(function (sum, item) { return sum + item.fare; }, 0, this);
};
这里对初始化函数作一些简要讲解,主要过程如下:
- 遍历已购商品列表(条码数组);
- 对每一个条码,分离出其编码信息;
- 若已购商品列表中已有该商品,则取出,否则从所有商品列表中查找该商品后取出;
- 将该商品的数量属性增加相应数值,同时将无优惠总价累加当前价格;
- 将该商品存至当前订单的商品列表中(哈希表);
- 遍历所有在“买二送一”活动中的商品,如果该商品在已购商品列表中,则标记其优惠信息;
- 递加获得此次购物应付的优惠后总价。
在上面的代码中,通过使用哈希表,避免了全规模的嵌套 for 循环。其中把第四点放在此处是为了降低复杂度的考虑(不需要在另外循环),在此题中所有列表均已固定,而非后期 Web 交互版本中的动态变更。
调用的 Item 类中的方法如下:
Item.js 的数量增加方法:
Item.prototype.addCount = function(raw_barcode) {
var bought_number = parseInt(raw_barcode.substring(11)) || 1;
this.count += bought_number;
this.fare = this.count * this.price;
return bought_number * this.price;
};
Item.js 的优惠计算方法:
Item.prototype.getPromotion = function() {
this.promotion = true;
this.free = Math.floor(this.count / 3);
this.fare = (this.count - this.free) * this.price;
};
需要注意的是,优惠的数量应该是 除 3 而非 除 2 ,理由不再解释。
结果输出
在整个输出的结果中,有很多块内容,分别用不同的函数实现,主要代码如下:
订单时间输出:
Order.prototype.getDateTime = function() {
return moment().format('YYYY年MM月DD日 HH:mm:ss');
};
上面用到了 MomentJS 的格式输出方法,各占位符就不解释了,是个人都看得懂。
购买和优惠列表输出: