Created
January 2, 2022 12:02
-
-
Save mitchallen/442df2791d8757a6f5ff56263c1a2fe0 to your computer and use it in GitHub Desktop.
JavaScript example of random picking from a list.
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
| // Author: Mitch Allen | |
| // File: pickone.js | |
| let pickOne = (list) => list[Math.floor(Math.random() * list.length)] | |
| let LIMIT = 5; | |
| let list = [...Array(LIMIT)].map(() => Math.random()); | |
| console.log(list); | |
| let item = pickOne(list); | |
| console.log("PICK: ", item); | |
| // check occurrences | |
| let PICK_LIMIT = 100; | |
| let picks = [...Array(PICK_LIMIT)].map(() => pickOne(list)); | |
| const occurrences = picks.reduce(function (acc, curr) { | |
| return acc[curr] ? ++acc[curr] : acc[curr] = 1, acc | |
| }, {}); | |
| console.log("PICK OCCURRENCES:") | |
| console.log(occurrences); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment