From 753135c8b209f9c49f525e0814340575c47115ff Mon Sep 17 00:00:00 2001 From: aozhiwei Date: Wed, 21 Sep 2022 19:30:19 +0800 Subject: [PATCH] 1 --- utils.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/utils.js b/utils.js index 07b9fb4..bb95454 100644 --- a/utils.js +++ b/utils.js @@ -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;