diff src/implab/components/StateMachine.js @ 0:fc2517695ee1

Initial commit, draft import of existing work
author cin
date Thu, 01 Jun 2017 13:20:03 +0300
parents
children 7d7059d2a810
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/implab/components/StateMachine.js	Thu Jun 01 13:20:03 2017 +0300
@@ -0,0 +1,34 @@
+define([ "dojo/_base/declare", "./safe", "./format" ], function(declare, safe, format) {
+    return declare(null, {
+        states : null,
+        
+        current : null,
+
+        constructor : function(opts) {
+            safe.argumentNotNull(opts, "opts");
+            safe.argumentNotNull(opts.states, "opts.states");
+            safe.argumentNotNull(opts.initial, "opts.initial");
+            
+            this.states = opts.states;
+            this.current =  opts.initial;
+            
+            if (safe.isNull(this.states[this.current]))
+                throw new Error("Invalid initial state " + this.current);
+        },
+        
+        move : function(input, noThrow) {
+            safe.argumentNotNull(input, "input");
+            
+            var next = this.states[this.current][input];
+            if(safe.isNull(next)) {
+                if (noThrow)
+                    return false;
+                else
+                    throw new Error(format("Invalid transition {0}-{1}->?", this.current, input));
+            } else {
+                this.current = next;
+                return true;
+            }
+        }
+    });
+});
\ No newline at end of file