getPrevNum(index) { console.log(index) // this.list[cloneData['index'] - 1]['ok_qty'] let ls = this.list[index - 1] if (ls['is_reported'] == 1) { let mateArr = this.list.filter((v) => v.group_id == ls['group_id']) // console.log(mateArr) // if (mateArr.length == 1) { // return mateArr[0]['ok_qty'] // } return { ok: mateArr.reduce((pre, x) => { return new Decimal(pre).add(new Decimal(x['ok_qty'])).toNumber() }, 0), ng: mateArr.reduce((pre, x) => { return new Decimal(pre).add(new Decimal(x['ng_qty'])).toNumber() }, 0), total: mateArr.reduce((pre, x) => { return new Decimal(pre).add(new Decimal(x['ok_qty']).add(new Decimal(x['ng_qty']))).toNumber() }, 0), } } let firstItemIndex = this.list.findIndex((v) => ls['group_id'] == v.group_id) console.log(firstItemIndex) if (firstItemIndex - 1 < 0) { return { ok: this.infoData.target_qty, ng: 0, total: this.infoData.target_qty } } else { let mateArr = this.list.filter((v) => v.group_id == this.list[firstItemIndex - 1]['group_id']) // if (mateArr.length == 1) { // return mateArr[0]['ok_qty'] // } return { ok: mateArr.reduce((pre, x) => { return new Decimal(pre).add(new Decimal(x['ok_qty'])).toNumber() }, 0), ng: mateArr.reduce((pre, x) => { return new Decimal(pre).add(new Decimal(x['ng_qty'])).toNumber() }, 0), total: mateArr.reduce((pre, x) => { return new Decimal(pre).add(new Decimal(x['ok_qty']).add(new Decimal(x['ng_qty']))).toNumber() }, 0), } } }, 优化一下
时间: 2024-01-27 17:05:23 浏览: 134
这段代码中可以优化的地方有:
1. 使用箭头函数简化代码:可以将函数内部的所有函数都改为箭头函数,让代码更加简洁易读。
2. 使用解构赋值:可以使用解构赋值来获取函数参数中的属性,让代码更加简洁。
3. 使用三元运算符:可以使用三元运算符来简化条件语句,让代码更加简洁。
4. 避免重复计算:可以避免重复计算,提高代码的效率。
5. 使用常量代替魔法数:可以使用常量来代替一些魔法数,让代码更加易读。
根据上述优化方案,可以改写代码如下:
```
getPrevNum = (index) => {
const OK_QTY = 'ok_qty';
const NG_QTY = 'ng_qty';
const IS_REPORTED = 'is_reported';
const GROUP_ID = 'group_id';
const TARGET_QTY = this.infoData.target_qty;
console.log(index);
const ls = this.list[index - 1];
if (ls[IS_REPORTED] === 1) {
const mateArr = this.list.filter((v) => v[GROUP_ID] === ls[GROUP_ID]);
return {
ok: mateArr.reduce((pre, x) => new Decimal(pre).add(new Decimal(x[OK_QTY])).toNumber(), 0),
ng: mateArr.reduce((pre, x) => new Decimal(pre).add(new Decimal(x[NG_QTY])).toNumber(), 0),
total: mateArr.reduce((pre, x) => new Decimal(pre).add(new Decimal(x[OK_QTY]).add(new Decimal(x[NG_QTY]))).toNumber(), 0),
};
}
const firstItemIndex = this.list.findIndex((v) => ls[GROUP_ID] === v[GROUP_ID]);
console.log(firstItemIndex);
if (firstItemIndex - 1 < 0) {
return { ok: TARGET_QTY, ng: 0, total: TARGET_QTY };
} else {
const mateArr = this.list.filter((v) => v[GROUP_ID] === this.list[firstItemIndex - 1][GROUP_ID]);
return {
ok: mateArr.reduce((pre, x) => new Decimal(pre).add(new Decimal(x[OK_QTY])).toNumber(), 0),
ng: mateArr.reduce((pre, x) => new Decimal(pre).add(new Decimal(x[NG_QTY])).toNumber(), 0),
total: mateArr.reduce((pre, x) => new Decimal(pre).add(new Decimal(x[OK_QTY]).add(new Decimal(x[NG_QTY]))).toNumber(), 0),
};
}
};
```
阅读全文