Skip to content

Instantly share code, notes, and snippets.

@davidc6
Last active June 15, 2021 08:00
Show Gist options
  • Save davidc6/786920c42985407d086b51f96f2c9ee5 to your computer and use it in GitHub Desktop.
Save davidc6/786920c42985407d086b51f96f2c9ee5 to your computer and use it in GitHub Desktop.
Loop the functional way, without mutating any variables
// this function allow us to build an array / list of objects that contain common props and props that are generated dynamically
const numberOfIterations = 10
const commonProps = {
propA: 1,
propB: 2
}
// -------
// -- 1 --
// -------
// initialize an empty array of totalPages and map over it to create a label for each button
const createListUsingMap = Array(numberOfIterations)
.fill(null)
.map((val, index) => {
return {
...commonProps,
propC: index + 1
}
})
// -------
// -- 2 --
// -------
// create a curried function that receives common props on first call and then additional props on further calls
const createObject = props => dynamicValue => {
return {
...props,
propC: dynamicValue
}
}
// This is a function that allows us to loop, decrement the value of numberOfIterations and recursively call itself
// target - a sort of accumulator / initial value that allows us to store data in it and pass it to the next call
// n - number of times that we need to "loop" / call the function
// fn - function that we need to call on each "iteration"
const loop = (target, n, fn) => {
// spread the target to merge previous data with new data
return n > 0 ? loop([ ...target, fn(n) ], n - 1, fn): target
}
// this will be an array that contains labels
const createListUsingRecursion = loop(
[],
numberOfIterations,
createObject(commonProps)
)
// tests both techniques
console.log(createListUsingMap)
console.log(createListUsingRecursion)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment