Last active
December 6, 2018 17:39
-
-
Save rafaelkendrik/532d70499bee717f788731006803ef89 to your computer and use it in GitHub Desktop.
Creating an array of results through a range: traditional mutation vs functional way.
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 playDice = sides => 1 + Math.floor(Math.random() * sides) | |
const playSixSidedDice = () => playDice(6) | |
// Pushing to Results (Traditional For) | |
const playSixSidedDices = rollTimes => { | |
let results = [] | |
for(let i = 0; i < rollTimes; i++) { | |
results.push(playSixSidedDice()) | |
} | |
return results | |
} | |
// Unchangeable Results (Map through an iterable Array of range indexes) | |
const range = i => [...Array(i).keys()] | |
const playSixSidedDices = rollTimes => | |
range(rollTimes).map(playSixSidedDice) | |
const results = playSixSidedDices(3) | |
// (example) results: [3, 4, 2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some alternatives using functional library for JavaScript:
Lodash: https://lodash.com/docs#range
Ramda: http://ramdajs.com/docs/#range