UNPKG

1.97 kBJavaScriptView Raw
1'use strict';
2
3// constructor
4
5function DFA() {
6 // alphabets are encoded by numbers in 16^N form, presenting its precedence
7 this.__highest_alphabet__ = 0x0;
8 this.__match_alphabets__ = {};
9 // states are union (bitwise OR) of its accepted alphabets
10 this.__initial_state__ = 0x0;
11 this.__accept_states__ = {};
12 // transitions are in the form: {prev_state: {alphabet: next_state}}
13 this.__transitions__ = {};
14 // actions take two parameters: step (line number), prev_state and alphabet
15 this.__actions__ = {};
16}
17
18// setters
19
20DFA.prototype.set_highest_alphabet = function (alphabet) {
21 this.__highest_alphabet__ = alphabet;
22};
23
24DFA.prototype.set_match_alphabets = function (matches) {
25 this.__match_alphabets__ = matches;
26};
27
28DFA.prototype.set_initial_state = function (initial) {
29 this.__initial_state__ = initial;
30};
31
32DFA.prototype.set_accept_states = function (accepts) {
33 for (var i = 0; i < accepts.length; i++) {
34 this.__accept_states__[accepts[i]] = true;
35 }
36};
37
38DFA.prototype.set_transitions = function (transitions) {
39 this.__transitions__ = transitions;
40};
41
42DFA.prototype.set_actions = function (actions) {
43 this.__actions__ = actions;
44};
45
46DFA.prototype.update_transition = function (state, alphabets) {
47 this.__transitions__[state] = Object.assign(
48 this.__transitions__[state] || Object(), alphabets
49 );
50};
51
52// methods
53
54DFA.prototype.execute = function (start, end) {
55 var state, step, alphabet;
56 for (state = this.__initial_state__, step = start; state && step < end; step++) {
57 for (alphabet = this.__highest_alphabet__; alphabet > 0x0; alphabet >>= 4) {
58 if ((state & alphabet)
59 && this.__match_alphabets__[alphabet].call(this, step, state, alphabet)) { break; }
60 }
61
62 this.__actions__(step, state, alphabet);
63
64 if (alphabet === 0x0) { break; }
65 state = this.__transitions__[state][alphabet] || 0x0;
66 }
67 return !!this.__accept_states__[state];
68};
69
70module.exports = DFA;
71
72/* vim: set ts=2 sw=2 et: */