Last active
April 27, 2025 13:24
-
-
Save jsoningram/08ec3839f5e9b28131f3db61a13a1163 to your computer and use it in GitHub Desktop.
Jackpot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const SymbolKeys = { | |
Bitcoin: 'bitcoin', | |
Cash: 'cash', | |
Cherry: 'cherry', | |
Diamond: 'diamond', | |
Gold: 'gold', | |
}; | |
// If all rollers equal one of the `Prize` keys, we'll multiply the value by | |
// the amount the user entered | |
const Prize = { | |
[SymbolKeys.Bitcoin]: 100, | |
[SymbolKeys.Cash]: 30, | |
[SymbolKeys.Cherry]: 10, | |
[SymbolKeys.Diamond]: 75, | |
[SymbolKeys.Gold]: 50, | |
}; | |
const Probabilities = { | |
[SymbolKeys.Bitcoin]: 0.05, | |
[SymbolKeys.Cash]: 0.25, | |
[SymbolKeys.Cherry]: 0.35, | |
[SymbolKeys.Diamond]: 0.15, | |
[SymbolKeys.Gold]: 0.2, | |
} | |
const getRandomWithProbability = (probabilities) => { | |
// Generate a random fp number between 0 and 1 exclusive | |
const randomNumber = Math.random(); | |
let acc = 0; | |
// Convert `probabilities` to a 2D array where each nested array contains | |
// a value and probability e.g., [['bitcoin', 0.05], ['cash', 0.25], ...] | |
for (const [value, probability] of Object.entries(probabilities)) { | |
// On each iteration we're adding the `probability` to an accumulator | |
acc += probability; | |
// If the accumulator is less than the random number we previously | |
// generated, return the current `value` | |
if (randomNumber < acc) { | |
return value; | |
} | |
} | |
return null; | |
} | |
const spin = (amount) => { | |
// Convert `Keys` to array of its values | |
const roller = Object.values(SymbolKeys); | |
const r1 = getRandomWithProbability(Probabilities); | |
const r2 = getRandomWithProbability(Probabilities); | |
const r3 = getRandomWithProbability(Probabilities); | |
const result = [ | |
roller[roller.indexOf(r1)], | |
roller[roller.indexOf(r2)], | |
roller[roller.indexOf(r3)], | |
]; | |
// Sets let you store unique values. If we have three of the same symbol in | |
// `result`, `set` size will be 1 indicating a JACKPOT | |
const set = new Set(result); | |
if (set.size === 1) { | |
let winningSymbol; | |
roller.some((item) => { | |
if (set.has(item)) { | |
winningSymbol = item; | |
return true; | |
} | |
return false; | |
}) | |
return { | |
prize: Prize[winningSymbol] * amount, | |
result, | |
} | |
} | |
return { | |
prize: null, | |
result, | |
} | |
} | |
console.log(spin(100)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment