Skip to content

Instantly share code, notes, and snippets.

@tr00gle
Created December 2, 2018 21:12
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 tr00gle/799e99b85083192d456a03270cbf593d to your computer and use it in GitHub Desktop.
Save tr00gle/799e99b85083192d456a03270cbf593d to your computer and use it in GitHub Desktop.
// More advanced application using closures and pure functions
const randomNum = n => Math.floor(Math.random() * n);
const fillRandomArray = (len, range) => Array.from({length: len}, () => randomNum(range))
const sorterCreator = (length, ceiling) => {
const buckets = {
low: 0,
mid: 0,
high: 0,
}
// create a random array of integers in interval from [0, ceiling)
const randomArray = fillRandomArray(length, ceiling);
// sorting callback for reduce
const sortingHat = (obj, num) => {
if (num < Math.floor(ceiling / 3)) {
obj.low++
} else if (num < Math.floor(ceiling / 3) * 2) {
obj.mid++
} else {
obj.high++
}
// uncomment to see accumulator status at every step
// console.log(`current accumulator status: ${JSON.stringify(acc)}`);
return obj
}
return () => randomArray.reduce(sortingHat, buckets);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment