// Since Node 10, we're using Mocha.
// You can use `chai` for assertions.
const chai = require("chai");
const assert = chai.assert;
// Uncomment the following line to disable truncating failure messages for deep equals, do:
// chai.config.truncateThreshold = 0;
// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.
// Uncomment the following to use the old assertions:
// const Test = require("@codewars/test-compat");
describe("Solution", function() {
const valuesToTest = [
[ 0.19485818770228258, "a" ],
[ 0.33340000000000000, "a" ],
[ 0.33350000000000000, "b" ],
[ 0.66660000000000000, "b" ],
[ 0.66670000000000000, "b" ],
[ 0.66680000000000000, "c" ],
[ 0.99990000000000000, "c" ],
[ 1.00000000000000000, "c" ],
]
valuesToTest.forEach(([ winningNumber, winnerName ]) => {
it(`return winner ${winnerName} for ${winningNumber}`, function() {
const rng = () => winningNumber
const winner = raffel(rng, [
{ name: "a", chance: 0.3334 },
{ name: "b", chance: 0.3333 },
{ name: "c", chance: 0.3333 },
])()
assert.equal(winner.name, winnerName)
});
});
it("throws when sum of chances > 1", function() {
const rng = () => 0.19485818770228258
try {
raffel(rng, [
{ name: "a", chance: 0.3334 },
{ name: "b", chance: 0.3333 },
{ name: "c", chance: 0.3334 },
]);
throw new Error("Did not throw");
} catch (e) {
assert.equal(e.message, "Sum of chance should be equal to 1");
}
})
it("throws when sum of chances < 1", function() {
const rng = () => 0.19485818770228258
try {
raffel(rng, [
{ name: "a", chance: 0.3333 },
{ name: "b", chance: 0.3333 },
{ name: "c", chance: 0.3333 },
]);
throw new Error("Did not throw");
} catch (e) {
assert.equal(e.message, "Sum of chance should be equal to 1");
}
})
it("works with Math.random", function() {
const winner = raffel(Math.random, [
{ name: "a", chance: 0.3334 },
{ name: "b", chance: 0.3333 },
{ name: "c", chance: 0.3333 },
])();
assert.isTrue(["a", "b", "c"].includes(winner.name))
})
it("1 million raffles distribuition with Math.random", function() {
const total = 1000000;
let i = 0;
const winners = [];
const myRaffel = raffel(Math.random, [
{ name: "a", chance: 0.3334 },
{ name: "b", chance: 0.3333 },
{ name: "c", chance: 0.3333 },
])
while(i < total - 1) {
i = i + 1
winners.push(myRaffel());
};
const sum = winners.reduce((acc, { name }) => {
acc[name] = (acc[name] ? acc[name] : 0) + 1
return acc
}, {});
const result = Object.entries(sum).map(([ name, winners ]) => ({ name, winners, percent: winners/(total*1.0) }))
console.log(result);
})
});