Created
January 25, 2015 23:09
-
-
Save thomd/03765a46675d4207b893 to your computer and use it in GitHub Desktop.
an example for functional programming
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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