Skip to content

Commit

Permalink
random.chance
Browse files Browse the repository at this point in the history
  • Loading branch information
lxjwlt committed Mar 5, 2017
1 parent 40010f4 commit 5c85ff4
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/util/random.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,42 @@ random.one = function () {
return random.array(Array.from(arguments));
};

random.chance = function (config) {
let keys = Object.keys(config);

let pointList = [0];

let proportion = keys.map((value, i) => {

if (value.match(/%$/)) {
value = parseFloat(value) / 100;
} else {
value = Number(value);
}

value = value || 0;

pointList.push((pointList[i]) + value);

return value;
});

let sum = proportion.reduce((last, cur) => last + cur);

let randomValue = random.float(0, sum);

let index = 0;

for (; index < pointList.length; index++) {
let next = pointList[index + 1] || Infinity;
if (randomValue > pointList[index] && randomValue < next) {
break;
}
}

let targetValue = config[keys[index]];

return typeof targetValue === 'function' ? targetValue() : targetValue;
};

module.exports = random;
38 changes: 38 additions & 0 deletions tests/src/util/random.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,42 @@ describe('random.js', function () {
});

});

describe('#chance', () => {

it('multi items', () => {
let numList = [];

for (let i = 0; i < 1000; i++) {
numList.push(random.chance({
'0.1': 1,
'0.7': 3,
'0.2': 2
}));
}

assert.include(numList, 1);
assert.include(numList, 2);
assert.include(numList, 3);
});

it('percent', () => {
let num = random.chance({
'200%': 1
});

assert.strictEqual(num, 1);
});

it('value is function', () => {
let num = random.chance({
'1': () => {
return 2;
}
});

assert.strictEqual(num, 2);
});

});
});

0 comments on commit 5c85ff4

Please sign in to comment.