Skip to content

Instantly share code, notes, and snippets.

@thomd
Created January 25, 2015 23:09
Show Gist options
  • Save thomd/03765a46675d4207b893 to your computer and use it in GitHub Desktop.
Save thomd/03765a46675d4207b893 to your computer and use it in GitHub Desktop.
an example for functional programming
// a functional race game
race({
time: 100,
positions: [1,1,1,1,1]
});
function race(state){
draw(state);
if(state.time){
race(step(state, move));
} else {
winner(state.positions)
}
}
function draw(state){
console.log('');
console.log(state.positions.map(times).join('\n'));
}
function times(position){
return new Array(position + 1).join('-')
}
function step(state, fn){
return {
time: state.time - 1,
positions: state.positions.map(fn)
}
}
function move(position){
return position + (Math.random() > 0.3 ? 1 : 0)
}
function winner(positions){
console.log("winner is", positions.indexOf(Math.max.apply(Math, positions)) + 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment