Skip to content

Instantly share code, notes, and snippets.

@stevekane
Last active August 26, 2015 21:49
Show Gist options
  • Save stevekane/5bd094def8aeeeb6de59 to your computer and use it in GitHub Desktop.
Save stevekane/5bd094def8aeeeb6de59 to your computer and use it in GitHub Desktop.
An overview of using generators to model processes that evolve over time
/*
There are often sequences of behavior that happen over time in complex applications. Sometimes these
are animations, sometimes sequences of async actions, and sometimes both. We would thus like to define
a simple way to express our intent without having to jump through incredible mental hurdles or use limited
features of libaries/frameworks (state transitions and tweens being chief among these) to get the work done.
Here is some code that shows an approach I have been developing for modeling these behaviors in javascript itself
using the re-entrant properties of generators.
*/
/*
We would like to model the following behavior:
-Fetch remote data (async waiting)
-Perform transition animation (async behavior with termination condition)
-Enable camera and remove white background after 300ms (async behavior)
Sequences of behavior should have the ability to be rewound from the point of beginning
which means that the operations should be backwards and forwards navigable (this is hardest part)
*/
//see here for spawn implementation https://gist.github.com/jakearchibald/31b89cba627924972ad6
//highest-level task
function * transitionToCamera (startTime, appState) {
let fetch = fetchRemoteData()
let transition = triggerTransition(appState)
let triggerCamera = triggerCamera()
let data = null
while (true) {
let {done, value} = fetch.next(Date.now())
if (done) {
data = value
break
}
else yield
}
while (true) {
let {done, value} = transition.next(Date.now())
if (done) break
else yield
}
while (true) {
let {done, value} = triggerCamera.next(Date.now())
if (done) break
else yield
}
}
function * getRemoteData () {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment