@@ -19,17 +19,17 @@ class CSP {
19
19
this . variables = variables ; // variables to be constrained
20
20
this . domains = domains ; // domain of each variable
21
21
this . constraints = { } ;
22
- for ( variable of this . variables ) {
22
+ for ( let variable of this . variables ) {
23
23
this . constraints [ variable ] = [ ] ;
24
- if ( Object . keys ( this . domains ) . indexOf ( variable ) == - 1 ) {
24
+ if ( ! member ( Object . keys ( this . domains ) , variable ) ) {
25
25
throw "Every variable should have a domain assigned to it." ;
26
26
}
27
27
}
28
28
}
29
29
30
30
addConstraint ( constraint ) {
31
- for ( variable of constraint . variables ) {
32
- if ( this . variables . indexOf ( variable ) == - 1 ) {
31
+ for ( let variable of constraint . variables ) {
32
+ if ( ! member ( this . variables , variable ) ) {
33
33
throw "Variable in constraint not in CSP" ;
34
34
} else {
35
35
this . constraints [ variable ] . push ( constraint ) ;
@@ -49,7 +49,7 @@ class CSP {
49
49
}
50
50
51
51
backtrackingSearch ( assignment ) {
52
- if ( assignment == null ) {
52
+ if ( ! assignment ) {
53
53
assignment = { } ;
54
54
}
55
55
// assignment is complete if every variable is assigned (our base case)
@@ -58,8 +58,7 @@ class CSP {
58
58
}
59
59
60
60
// get all variables in the CSP but not in the assignment
61
- let unassigned = this . variables . filter ( ( v ) => Object . keys ( assignment ) . indexOf ( v ) == - 1 ) ;
62
-
61
+ let unassigned = this . variables . filter ( ( v ) => ! member ( Object . keys ( assignment ) , v ) ) ;
63
62
// get every possible domain value of the first unassigned variable
64
63
let first = unassigned [ 0 ] ;
65
64
for ( let value of this . domains [ first ] ) {
@@ -79,9 +78,30 @@ class CSP {
79
78
}
80
79
}
81
80
81
+ // array membership helper function
82
+ function member ( array , element ) {
83
+ if ( array . length == 0 ) {
84
+ return false ;
85
+ }
86
+ if ( typeof array [ 0 ] == typeof element ) {
87
+ return array . indexOf ( element ) > - 1 ;
88
+ }
89
+ if ( typeof array [ 0 ] == 'string' && typeof element == 'number' ) {
90
+ return array . indexOf ( element . toString ( ) ) > - 1 ;
91
+ }
92
+ for ( let item of array ) {
93
+ if ( element == item ) {
94
+ return true ;
95
+ }
96
+ }
97
+ return false ;
98
+ }
99
+
100
+
82
101
let _exports = {
83
102
Constraint : Constraint ,
84
- CSP : CSP
103
+ CSP : CSP ,
104
+ member : member
85
105
} ;
86
106
87
107
if ( typeof window === 'undefined' ) {
0 commit comments