This commit is contained in:
aozhiwei 2022-09-21 19:30:19 +08:00
parent 6a6a58c944
commit 753135c8b2

View File

@ -251,6 +251,36 @@ function isPureNumberStr(str) {
return true;
}
function randItemByWeight(list, fieldName) {
const ret = {
'index': -1,
'item': null
};
let totalSpace = function () {
let space = 0;
list.forEach((item) => {
space += Number(item[fieldName]);
});
return space;
}();
if (totalSpace > 0) {
const rand = randRange(0, totalSpace - 1);
let currSpace = 0;
for (let i = 0; i < list.length; ++i) {
currSpace += Number(list[i][fieldName]);
//console.log(currSpace, rand, totalSpace, list);
if (rand < currSpace) {
ret['index'] = i;
ret['item'] = list[i];
break;
}
}
} else {
console.log('randItemByWeight error:', list);
}
return ret;
}
exports.rspErr = rspErr;
exports.rspOk = rspOk;
exports.rspData = rspData;
@ -266,6 +296,7 @@ exports.getHourSeconds = getHourSeconds;
exports.formatDate = formatDate;
exports.pad = pad;
exports.randRange = randRange;
exports.randItemByWeight = randItemByWeight;
exports.jsonEncode = jsonEncode;
exports.prettyJsonEncode = prettyJsonEncode;
exports.jsonDecode = jsonDecode;