Skip to content

Instantly share code, notes, and snippets.

@rafaelkendrik
Last active December 6, 2018 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaelkendrik/532d70499bee717f788731006803ef89 to your computer and use it in GitHub Desktop.
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.
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]
@rafaelkendrik
Copy link
Author

rafaelkendrik commented Mar 15, 2018

Note: Any performance comparing has been done yet.

@rafaelkendrik
Copy link
Author

rafaelkendrik commented Mar 18, 2018

Results: Tested 20x, rolling dices 1000 times
Array and Map had a performance ~30% slower than For.
https://jsperf.com/ranges-mutable-vs-immutable-js

@rafaelkendrik
Copy link
Author

Some alternatives using functional library for JavaScript:
Lodash: https://lodash.com/docs#range
Ramda: http://ramdajs.com/docs/#range

@rafaelkendrik
Copy link
Author

rafaelkendrik commented Dec 6, 2018

Alternative using Array.from:

Array.from({length: 5}, (v, i) => i);

MDN - full example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment