Skip to content

Instantly share code, notes, and snippets.

@necoco
Last active August 29, 2015 14:12
Show Gist options
  • Save necoco/b2687696dd8550d1173c to your computer and use it in GitHub Desktop.
Save necoco/b2687696dd8550d1173c to your computer and use it in GitHub Desktop.
fp sample
W = 800
H = 600
R = 50
class Sprite
constructor: ()->
init: ()->
@x = Math.random() * W
@y = Math.random() * H
@color = "#" + Math.floor((Math.random() * 0xffffff)).toString(16)
@
move: ()->
@x = Math.random() * W
@y = Math.random() * H
clone: ()->
sprite = new Sprite()
sprite.x = @x
sprite.y = @y
sprite.color = @color
sprite
draw: (c)->
c.fillStyle = @color
c.fillRect(@x, @y, R, R)
class World
constructor: ()->
@sprites = for x in [0...10000]
sprite = new Sprite()
sprite.init()
drawObjective: (c)->
for sprite in @sprites
sprite.move()
sprite.draw c
updateFunctional: (sprites)->
_.map sprites, (sprite)->
value = sprite.clone()
value.x = Math.random() * W
value.y = Math.random() * H
value
updateFunctionalOptimized: (sprites)->
_.map sprites, (sprite)->
sprite.x = Math.random() * W
sprite.y = Math.random() * H
sprite
drawFunctional: (c, update)->
newValue = update(@sprites)
_.map newValue, (sprite)->
c.fillStyle = sprite.color
c.fillRect(sprite.x, sprite.y, R, R)
@sprites = newValue
reactiveFunctional: (c)->
@drawFunctional c, @updateFunctional.bind(@)
reactiveFunctionalOptimized: (c)->
@drawFunctional c, @updateFunctionalOptimized.bind(@)
window.onload = ->
canvas = document.getElementById 'canvas'
context = canvas.getContext('2d')
world =new World()
T = 100
time = Date.now()
for i in [0...T]
world.drawObjective context
console.log "objective", (Date.now() - time) / T
time = Date.now()
for i in [0...T]
world.reactiveFunctional context
console.log "functional", (Date.now() - time) / T
time = Date.now()
for i in [0...T]
world.reactiveFunctionalOptimized context
console.log "functional optimized", (Date.now() - time) / T
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment