Javascript version of squirrel state machine