Implementation of State Machine Pattern in JavaScript