Skip to content

Instantly share code, notes, and snippets.

@stevekane
Last active August 29, 2015 14:07
Show Gist options
  • Save stevekane/6ee014d5be9e6f6c0394 to your computer and use it in GitHub Desktop.
Save stevekane/6ee014d5be9e6f6c0394 to your computer and use it in GitHub Desktop.
A quick illustration of the compact and readable nature of iteration with reducers
/*
This gist is just a quick example of the same function written
in a composable manner (using prodash.js). Please understand
that the functions exported by prodash are almost ALL curried
by default allowing them to be partially applied.
The goal of this code is to iterate through a list of "particles"
and return a Float32Array of their x,y,z components. Only living
particles should be included.
*/
//declarative or "point free" style
let Float32s = (arg) => new Float32Array(arg)
let flatPositions = compose([checking("living"), plucking("position"), cat])
let positionsArray = compose([Float32s, sequence(flatPositions)])
//here we get our result
let positions = positionsArray(particles)
//imperative style
let buildFlatPositions (particles) => {
let out = []
let particle
for (let i = 0; i < particles.length; ++i) {
particle = particles[i]
if (!!particle.living) {
out.push(particle.position[0])
out.push(particle.position[1])
out.push(particle.position[2])
}
}
return new Float32Array(out)
}
//result
let positions = buildFlatPositions(particles)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment