遇到一个算法问题 js的 不知道怎么优化比较好
const getPayList = (list: { name: string; pay: number }[]) => {
const total = list.reduce((prev, { pay }) => prev + pay, 0);
const average = Math.round((total / list.length) * 100);
const newList = list
.map(({ pay, ...other }) => {
return {
needPay: average - pay * 100,
pay: pay * 100,
...other,
};
})
.sort(({ needPay: a }, { needPay: b }) => b - a);
const get = newList.filter(({ needPay }) => needPay < 0);
const give = newList.filter(({ needPay }) => needPay > 0);
const toPayRes = [];
let currentGiveIdx = 0;
const toPay = (item) => {
if (currentGiveIdx >= give.length) return;
const currentGive = give[currentGiveIdx];
const { needPay } = currentGive;
const total = needPay + item.needPay;
if (total > 0) {
give[currentGiveIdx].needPay = total;
toPayRes.push(`${currentGive.name}转${Math.abs(item.needPay) / 100}给${item.name}`);
item.needPay = 0;
} else if (total === 0) {
item.needPay = total;
currentGiveIdx += 1;
toPayRes.push(`${currentGive.name}转${currentGive.needPay / 100}给${item.name}`);
} else {
currentGiveIdx += 1;
item.needPay = total;
toPayRes.push(`${currentGive.name}转${currentGive.needPay / 100}给${item.name}`);
toPay(item);
}
};
get.forEach((item) => {
toPay(item);
});
};
js
新手,用自带的方法写烦了。。跑去学了下lodash
。第一次用,有不对的恳请指出输入
输出
js
代码