Instantly share code, notes, and snippets.

Embed
What would you like to do?
State pattern with functions
let createContext = function(firstState) {
let context = {
count: 100,
next: firstState,
};
return function(message) {
context = context.next(message, context);
return context;
};
};
function green(message, context) {
console.log('Green ' + context.count + ' ' + message);
context.count++;
context.next = red;
return context;
}
function red(message, context) {
console.log('Red ' + context.count + ' ' + message);
context.count++;
context.next = green;
return context;
}
(function() {
let nextState = createContext(green);
for (var i = 0; i < 5; i++) {
nextState('message ' + i);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment