├── demo
├── .gitignore
├── assets
│ ├── img
│ │ ├── glyphicons-halflings-white.png
│ │ ├── pacman.gif
│ │ └── glyphicons-halflings.png
│ ├── ico
│ │ ├── favicon.ico
│ │ ├── apple-touch-icon-57-precomposed.png
│ │ ├── apple-touch-icon-72-precomposed.png
│ │ ├── apple-touch-icon-114-precomposed.png
│ │ └── apple-touch-icon-144-precomposed.png
│ ├── css
│ │ ├── styles.css
│ │ └── bootstrap-responsive.min.css
│ └── js
│ │ ├── html5shiv-pre3.6.js
│ │ ├── app.js
│ │ └── bootstrap.min.js
├── README.md
└── index.html
├── .gitignore
├── test
├── index.html
├── qunit
│ ├── qunit-1.11.0.css
│ └── qunit-1.11.0.js
└── tests.js
├── LICENSE
├── README.md
└── sudoku.js
/demo/.gitignore:
--------------------------------------------------------------------------------
1 | .c9revisions
2 |
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .c9revisions
2 | ref
3 | archive
4 |
--------------------------------------------------------------------------------
/demo/assets/img/glyphicons-halflings-white.png:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/demo/assets/img/pacman.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/whatever/sudoku.js/master/demo/assets/img/pacman.gif
--------------------------------------------------------------------------------
/demo/assets/ico/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/whatever/sudoku.js/master/demo/assets/ico/favicon.ico
--------------------------------------------------------------------------------
/demo/assets/img/glyphicons-halflings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/whatever/sudoku.js/master/demo/assets/img/glyphicons-halflings.png
--------------------------------------------------------------------------------
/demo/assets/ico/apple-touch-icon-57-precomposed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/whatever/sudoku.js/master/demo/assets/ico/apple-touch-icon-57-precomposed.png
--------------------------------------------------------------------------------
/demo/assets/ico/apple-touch-icon-72-precomposed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/whatever/sudoku.js/master/demo/assets/ico/apple-touch-icon-72-precomposed.png
--------------------------------------------------------------------------------
/demo/assets/ico/apple-touch-icon-114-precomposed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/whatever/sudoku.js/master/demo/assets/ico/apple-touch-icon-114-precomposed.png
--------------------------------------------------------------------------------
/demo/assets/ico/apple-touch-icon-144-precomposed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/whatever/sudoku.js/master/demo/assets/ico/apple-touch-icon-144-precomposed.png
--------------------------------------------------------------------------------
/demo/README.md:
--------------------------------------------------------------------------------
1 | Sudoku.js Demo Page
2 | ===================
3 |
4 | Simple demo page for the Sudoku puzzle generator and solver library [Sudoku.js](https://github.com/robatron/sudoku.js).
5 |
6 | View it live [here](http://htmlpreview.github.com/?https://github.com/robatron/sudoku.js/blob/master/demo/index.html).
7 |
--------------------------------------------------------------------------------
/test/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Sudoku.js Test Suite
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/demo/assets/css/styles.css:
--------------------------------------------------------------------------------
1 | /* Styles for the Sudoku.js demo page
2 | */
3 |
4 | body {
5 | padding-top: 60px;
6 | padding-bottom: 40px;
7 | }
8 |
9 | .container-narrow {
10 | /* Custom, narrow container */
11 | margin: 0 auto;
12 | max-width: 600px;
13 | }
14 |
15 | #footer {
16 | margin-top: 120px;
17 | }
18 |
19 | #sudoku-board {
20 | border: 2px solid black;
21 | }
22 |
23 | #sudoku-board td {
24 | padding: 0px;
25 | margin: 0px;
26 | }
27 |
28 | #sudoku-board input.square {
29 | display: block;
30 | margin-left:auto;
31 | margin-right:auto;
32 | margin-bottom:0px;
33 | width: 63px;
34 | height: 45px;
35 | padding: 0px;
36 | font-size: 40px;
37 | text-align: center;
38 | }
39 |
40 | #sudoku-board .border-right {
41 | border-right: 2px solid black;
42 | }
43 |
44 | #sudoku-board .border-bottom {
45 | border-bottom: 2px solid black;
46 | }
47 |
48 | .green-text {
49 | color: ForestGreen !important;
50 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2014 Rob McGuire-Dale
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6 |
7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 |
9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10 |
--------------------------------------------------------------------------------
/demo/assets/js/html5shiv-pre3.6.js:
--------------------------------------------------------------------------------
1 | /*! HTML5 Shiv vpre3.6 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
2 | Uncompressed source: https://github.com/aFarkas/html5shiv */
3 | (function(a,b){function h(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x",d.insertBefore(c.lastChild,d.firstChild)}function i(){var a=l.elements;return typeof a=="string"?a.split(" "):a}function j(a){var b={},c=a.createElement,f=a.createDocumentFragment,g=f();a.createElement=function(a){if(!l.shivMethods)return c(a);var f;return b[a]?f=b[a].cloneNode():e.test(a)?f=(b[a]=c(a)).cloneNode():f=c(a),f.canHaveChildren&&!d.test(a)?g.appendChild(f):f},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+i().join().replace(/\w+/g,function(a){return c(a),g.createElement(a),'c("'+a+'")'})+");return n}")(l,g)}function k(a){var b;return a.documentShived?a:(l.shivCSS&&!f&&(b=!!h(a,"article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio{display:none}canvas,video{display:inline-block;*display:inline;*zoom:1}[hidden]{display:none}audio[controls]{display:inline-block;*display:inline;*zoom:1}mark{background:#FF0;color:#000}")),g||(b=!j(a)),b&&(a.documentShived=b),a)}var c=a.html5||{},d=/^<|^(?:button|form|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^<|^(?:a|b|button|code|div|fieldset|form|h1|h2|h3|h4|h5|h6|i|iframe|img|input|label|li|link|ol|option|p|param|q|script|select|span|strong|style|table|tbody|td|textarea|tfoot|th|thead|tr|ul)$/i,f,g;(function(){var c=b.createElement("a");c.innerHTML="",f="hidden"in c,f&&typeof injectElementWithStyles=="function"&&injectElementWithStyles("#modernizr{}",function(b){b.hidden=!0,f=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle).display=="none"}),g=c.childNodes.length==1||function(){try{b.createElement("a")}catch(a){return!0}var c=b.createDocumentFragment();return typeof c.cloneNode=="undefined"||typeof c.createDocumentFragment=="undefined"||typeof c.createElement=="undefined"}()})();var l={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:k};a.html5=l,k(b)})(this,document)
--------------------------------------------------------------------------------
/test/qunit/qunit-1.11.0.css:
--------------------------------------------------------------------------------
1 | /**
2 | * QUnit v1.11.0 - A JavaScript Unit Testing Framework
3 | *
4 | * http://qunitjs.com
5 | *
6 | * Copyright 2012 jQuery Foundation and other contributors
7 | * Released under the MIT license.
8 | * http://jquery.org/license
9 | */
10 |
11 | /** Font Family and Sizes */
12 |
13 | #qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult {
14 | font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
15 | }
16 |
17 | #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; }
18 | #qunit-tests { font-size: smaller; }
19 |
20 |
21 | /** Resets */
22 |
23 | #qunit-tests, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter {
24 | margin: 0;
25 | padding: 0;
26 | }
27 |
28 |
29 | /** Header */
30 |
31 | #qunit-header {
32 | padding: 0.5em 0 0.5em 1em;
33 |
34 | color: #8699a4;
35 | background-color: #0d3349;
36 |
37 | font-size: 1.5em;
38 | line-height: 1em;
39 | font-weight: normal;
40 |
41 | border-radius: 5px 5px 0 0;
42 | -moz-border-radius: 5px 5px 0 0;
43 | -webkit-border-top-right-radius: 5px;
44 | -webkit-border-top-left-radius: 5px;
45 | }
46 |
47 | #qunit-header a {
48 | text-decoration: none;
49 | color: #c2ccd1;
50 | }
51 |
52 | #qunit-header a:hover,
53 | #qunit-header a:focus {
54 | color: #fff;
55 | }
56 |
57 | #qunit-testrunner-toolbar label {
58 | display: inline-block;
59 | padding: 0 .5em 0 .1em;
60 | }
61 |
62 | #qunit-banner {
63 | height: 5px;
64 | }
65 |
66 | #qunit-testrunner-toolbar {
67 | padding: 0.5em 0 0.5em 2em;
68 | color: #5E740B;
69 | background-color: #eee;
70 | overflow: hidden;
71 | }
72 |
73 | #qunit-userAgent {
74 | padding: 0.5em 0 0.5em 2.5em;
75 | background-color: #2b81af;
76 | color: #fff;
77 | text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
78 | }
79 |
80 | #qunit-modulefilter-container {
81 | float: right;
82 | }
83 |
84 | /** Tests: Pass/Fail */
85 |
86 | #qunit-tests {
87 | list-style-position: inside;
88 | }
89 |
90 | #qunit-tests li {
91 | padding: 0.4em 0.5em 0.4em 2.5em;
92 | border-bottom: 1px solid #fff;
93 | list-style-position: inside;
94 | }
95 |
96 | #qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running {
97 | display: none;
98 | }
99 |
100 | #qunit-tests li strong {
101 | cursor: pointer;
102 | }
103 |
104 | #qunit-tests li a {
105 | padding: 0.5em;
106 | color: #c2ccd1;
107 | text-decoration: none;
108 | }
109 | #qunit-tests li a:hover,
110 | #qunit-tests li a:focus {
111 | color: #000;
112 | }
113 |
114 | #qunit-tests li .runtime {
115 | float: right;
116 | font-size: smaller;
117 | }
118 |
119 | .qunit-assert-list {
120 | margin-top: 0.5em;
121 | padding: 0.5em;
122 |
123 | background-color: #fff;
124 |
125 | border-radius: 5px;
126 | -moz-border-radius: 5px;
127 | -webkit-border-radius: 5px;
128 | }
129 |
130 | .qunit-collapsed {
131 | display: none;
132 | }
133 |
134 | #qunit-tests table {
135 | border-collapse: collapse;
136 | margin-top: .2em;
137 | }
138 |
139 | #qunit-tests th {
140 | text-align: right;
141 | vertical-align: top;
142 | padding: 0 .5em 0 0;
143 | }
144 |
145 | #qunit-tests td {
146 | vertical-align: top;
147 | }
148 |
149 | #qunit-tests pre {
150 | margin: 0;
151 | white-space: pre-wrap;
152 | word-wrap: break-word;
153 | }
154 |
155 | #qunit-tests del {
156 | background-color: #e0f2be;
157 | color: #374e0c;
158 | text-decoration: none;
159 | }
160 |
161 | #qunit-tests ins {
162 | background-color: #ffcaca;
163 | color: #500;
164 | text-decoration: none;
165 | }
166 |
167 | /*** Test Counts */
168 |
169 | #qunit-tests b.counts { color: black; }
170 | #qunit-tests b.passed { color: #5E740B; }
171 | #qunit-tests b.failed { color: #710909; }
172 |
173 | #qunit-tests li li {
174 | padding: 5px;
175 | background-color: #fff;
176 | border-bottom: none;
177 | list-style-position: inside;
178 | }
179 |
180 | /*** Passing Styles */
181 |
182 | #qunit-tests li li.pass {
183 | color: #3c510c;
184 | background-color: #fff;
185 | border-left: 10px solid #C6E746;
186 | }
187 |
188 | #qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; }
189 | #qunit-tests .pass .test-name { color: #366097; }
190 |
191 | #qunit-tests .pass .test-actual,
192 | #qunit-tests .pass .test-expected { color: #999999; }
193 |
194 | #qunit-banner.qunit-pass { background-color: #C6E746; }
195 |
196 | /*** Failing Styles */
197 |
198 | #qunit-tests li li.fail {
199 | color: #710909;
200 | background-color: #fff;
201 | border-left: 10px solid #EE5757;
202 | white-space: pre;
203 | }
204 |
205 | #qunit-tests > li:last-child {
206 | border-radius: 0 0 5px 5px;
207 | -moz-border-radius: 0 0 5px 5px;
208 | -webkit-border-bottom-right-radius: 5px;
209 | -webkit-border-bottom-left-radius: 5px;
210 | }
211 |
212 | #qunit-tests .fail { color: #000000; background-color: #EE5757; }
213 | #qunit-tests .fail .test-name,
214 | #qunit-tests .fail .module-name { color: #000000; }
215 |
216 | #qunit-tests .fail .test-actual { color: #EE5757; }
217 | #qunit-tests .fail .test-expected { color: green; }
218 |
219 | #qunit-banner.qunit-fail { background-color: #EE5757; }
220 |
221 |
222 | /** Result */
223 |
224 | #qunit-testresult {
225 | padding: 0.5em 0.5em 0.5em 2.5em;
226 |
227 | color: #2b81af;
228 | background-color: #D2E0E6;
229 |
230 | border-bottom: 1px solid white;
231 | }
232 | #qunit-testresult .module-name {
233 | font-weight: bold;
234 | }
235 |
236 | /** Fixture */
237 |
238 | #qunit-fixture {
239 | position: absolute;
240 | top: -10000px;
241 | left: -10000px;
242 | width: 1000px;
243 | height: 1000px;
244 | }
245 |
--------------------------------------------------------------------------------
/demo/index.html:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
10 | Sudoku.js Demo
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
24 |
25 |
26 |
27 |
29 |
31 |
33 |
35 |
36 |
37 |
38 |
39 |
40 |
Loading...
41 |
42 |
43 |
44 |
45 |
Sudoku.js Demo
46 |
47 | A quick-n-dirty demonstration of
48 |
49 | Sudoku.js.
50 |
51 |
52 |
53 | This demonstrates the following features of the Sudoku.js
54 | library:
55 |
56 |
71 |
72 |
73 |
74 | Please visit the
75 |
76 | project page for more information.
77 |
78 |
79 |
80 |
81 |
82 |
120 |
121 |
122 |
126 |
127 |
128 |
134 |
135 |
136 |
139 |
140 |
141 |
142 |
145 |
146 |
147 |
148 |
149 |
150 |
155 |
160 |
161 |
162 |
163 |
170 |
171 |
172 |
173 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Sudoku.js
2 | ==========
3 |
4 | A Sudoku puzzle **generator** and **solver** JavaScript library.
5 |
6 | Check out the [online demo][demo] to see it in action.
7 |
8 | Implementation ideas borrowed from
9 | ["Solving Every Sudoku Puzzle"][norvig-sudoku] by
10 | [Peter Norvig][norvig], and a [generator/solver][anderson-sudoku] by
11 | [Michael Anderson][anderson].
12 |
13 | [demo]:http://htmlpreview.github.io/?https://github.com/robatron/sudoku.js/blob/master/demo/index.html
14 |
15 | Intro
16 | --------------------------------------------------------------------------------
17 |
18 | Puzzles are represented by a string of digits, 1-9, and '.' as spaces. Each
19 | character represents a square, e.g.,
20 |
21 | "52...6.........7.13...........4..8..6......5...........418.........3..2...87....."
22 |
23 | Represents the following board:
24 |
25 | 5 2 . | . . 6 | . . .
26 | . . . | . . . | 7 . 1
27 | 3 . . | . . . | . . .
28 | ------+-------+------
29 | . . . | 4 . . | 8 . .
30 | 6 . . | . . . | . 5 .
31 | . . . | . . . | . . .
32 | ------+-------+------
33 | . 4 1 | 8 . . | . . .
34 | . . . | . 3 . | . 2 .
35 | . . 8 | 7 . . | . . .
36 |
37 | (See the included [converstion functions](#board-string-%E2%86%94-grid) to
38 | convert between string representations and grids, i.e., two-dimensional arrays.)
39 |
40 |
41 | Generate a Sudoku puzzle
42 | --------------------------------------------------------------------------------
43 |
44 | Generage a Sudoku puzzle of a particular difficulty, e.g,
45 |
46 | ```javascript
47 | >>> sudoku.generate("easy")
48 | "672819345193..4862485..3197824137659761945283359...714.38..1426.174.6.38.463...71"
49 |
50 | >>> sudoku.generate("medium")
51 | "8.4.71.9.976.3....5.196....3.7495...692183...4.5726..92483591..169847...753612984"
52 |
53 | >>> sudoku.generate("hard")
54 | ".17..69..356194.2..89..71.6.65...273872563419.43...685521......798..53..634...59."
55 | ```
56 |
57 | Valid difficulties are as follows, and represent the number of given squares:
58 |
59 | "easy": 62
60 | "medium": 53
61 | "hard": 44
62 | "very-hard": 35
63 | "insane": 26
64 | "inhuman": 17
65 |
66 |
67 | You may also enter a custom number of squares to give, e.g.,
68 |
69 | ```javascript
70 | >>> sudoku.generate(60)
71 | "8941376521532687497269548...72.9158.538.4219..19.852..3874.69.52415793689658.34.."
72 | ```
73 |
74 | The number of givens must be a number between 17 and 81 inclusive. If it's
75 | outside of that range, the number of givens will be set to the closest bound,
76 | e.g., 0 will be treated as 17, and 100 as 81.
77 |
78 |
79 | By default, the puzzles should have unique solutions, unless you set `unique` to
80 | false, e.g.,
81 |
82 | ```javascript
83 | sudoku.generate("easy", false)
84 | ```
85 |
86 | Note: **Puzzle uniqueness is not yet implemented**, so puzzles are *not*
87 | guaranteed to have unique solutions.
88 |
89 |
90 | Solve a Sudoku puzzle
91 | --------------------------------------------------------------------------------
92 |
93 | Solve a Sudoku puzzle given a Sudoku puzzle represented as a string, e.g.,
94 |
95 | ```javascript
96 | >>> sudoku.solve(".17..69..356194.2..89..71.6.65...273872563419.43...685521......798..53..634...59.");
97 | "217386954356194728489257136165948273872563419943712685521439867798625341634871592"
98 | ```
99 |
100 |
101 | Board string ↔ grid
102 | --------------------------------------------------------------------------------
103 |
104 | Board string → grid:
105 |
106 | ```javascript
107 | >>> sudoku.board_string_to_grid("23.94.67.8..3259149..76.32.1.....7925.321.4864..68.5317..1....96598721433...9...7")
108 | [
109 | ["2","3",".","9","4",".","6","7","."],
110 | ["8",".",".","3","2","5","9","1","4"],
111 | ["9",".",".","7","6",".","3","2","."],
112 | ["1",".",".",".",".",".","7","9","2"],
113 | ["5",".","3","2","1",".","4","8","6"],
114 | ["4",".",".","6","8",".","5","3","1"],
115 | ["7",".",".","1",".",".",".",".","9"],
116 | ["6","5","9","8","7","2","1","4","3"],
117 | ["3",".",".",".","9",".",".",".","7"]
118 | ]
119 | ```
120 |
121 | Board grid → string:
122 |
123 | ```javascript
124 | >>> sudoku.board_grid_to_string([
125 | ["2","3",".","9","4",".","6","7","."],
126 | ["8",".",".","3","2","5","9","1","4"],
127 | ["9",".",".","7","6",".","3","2","."],
128 | ["1",".",".",".",".",".","7","9","2"],
129 | ["5",".","3","2","1",".","4","8","6"],
130 | ["4",".",".","6","8",".","5","3","1"],
131 | ["7",".",".","1",".",".",".",".","9"],
132 | ["6","5","9","8","7","2","1","4","3"],
133 | ["3",".",".",".","9",".",".",".","7"]
134 | ])
135 | "23.94.67.8..3259149..76.32.1.....7925.321.4864..68.5317..1....96598721433...9...7"
136 | ```
137 |
138 |
139 | Get candidates
140 | --------------------------------------------------------------------------------
141 |
142 | Get a grid of squares and their candidate values, propagating constraints, i.e.,
143 | candidates restrict their peer candidates.
144 |
145 | ```javascript
146 | >>> sudoku.get_candidates("4.25..389....4.265..523.147..1652.7.6..1945322543876915....3.1....4..9.....8....3")
147 | [
148 | ["4", "167", "2", "5", "167", "16", "3", "8", "9" ],
149 | ["13789", "13789", "3789", "79", "4", "189", "2", "6", "5" ],
150 | ["89", "689", "5", "2", "3", "689", "1", "4", "7" ],
151 | ["389", "389", "1", "6", "5", "2", "48", "7", "48" ],
152 | ["6", "78", "78", "1", "9", "4", "5", "3", "2" ],
153 | ["2", "5", "4", "3", "8", "7", "6", "9", "1" ],
154 | ["5", "246789", "6789", "79", "267", "3", "478", "1", "468"],
155 | ["1378", "123678", "3678", "4", "1267", "156", "9", "25", "68" ],
156 | ["179", "124679", "679", "8", "1267", "1569", "47", "25", "3" ]
157 | ]
158 | ```
159 |
160 |
161 | Print a board to the console
162 | ----------------------------
163 |
164 | ```javascript
165 | >>> sudoku.print_board(".17..69..356194.2..89..71.6.65...273872563419.43...685521......798..53..634...59.");
166 | . 1 7 . . 6 9 . .
167 | 3 5 6 1 9 4 . 2 .
168 | . 8 9 . . 7 1 . 6
169 |
170 | . 6 5 . . . 2 7 3
171 | 8 7 2 5 6 3 4 1 9
172 | . 4 3 . . . 6 8 5
173 |
174 | 5 2 1 . . . . . .
175 | 7 9 8 . . 5 3 . .
176 | 6 3 4 . . . 5 9 .
177 | ```
178 |
179 |
180 | References:
181 | -----------
182 |
183 | - ["Solving Every Sudoku Puzzle"][norvig-sudoku] by [Peter Norvig][norvig]
184 | - Sudoku [generator/solver][anderson-sudoku] for Mac OS X by [Michael Anderson][anderson]
185 | - [95 Sudoku Puzzles][95-sudokus]
186 | - Andrew Stuart's [online Sudoku Solver][stuart-sudoku]
187 |
188 |
189 | [norvig-sudoku]: http://norvig.com/sudoku.html
190 | [anderson-sudoku]: https://github.com/andermic/cousins/tree/master/sudoku
191 | [stuart-sudoku]: http://www.sudokuwiki.org/sudoku.htm
192 | [95-sudokus]: http://magictour.free.fr/top95
193 | [norvig]: http://norvig.com
194 | [anderson]: https://github.com/andermic/
195 |
196 |
197 |
198 | License:
199 | --------
200 |
201 | The MIT License (MIT)
202 |
203 | Copyright (c) 2014 Rob McGuire-Dale
204 |
205 | Permission is hereby granted, free of charge, to any person obtaining a copy
206 | of this software and associated documentation files (the "Software"), to deal
207 | in the Software without restriction, including without limitation the rights
208 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
209 | copies of the Software, and to permit persons to whom the Software is
210 | furnished to do so, subject to the following conditions:
211 |
212 | The above copyright notice and this permission notice shall be included in all
213 | copies or substantial portions of the Software.
214 |
215 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
216 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
217 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
218 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
219 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
220 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
221 | SOFTWARE.
222 |
--------------------------------------------------------------------------------
/demo/assets/js/app.js:
--------------------------------------------------------------------------------
1 | /*
2 | Quick-n-dirty demo page for Sudoku.js.
3 |
4 | For more information, please see https://github.com/robatron/sudoku.js
5 | */
6 |
7 | // Selectors
8 | var BOARD_SEL = "#sudoku-board";
9 | var TABS_SEL = "#generator-tabs";
10 | var MESSAGE_SEL = "#message";
11 | var PUZZLE_CONTROLS_SEL = "#puzzle-controls";
12 | var IMPORT_CONTROLS_SEL = "#import-controls";
13 | var SOLVER_CONTROLS_SEL = "#solver-controls";
14 |
15 | // Boards
16 | // TODO: Cache puzzles as strings instead of grids to cut down on conversions?
17 | var boards = {
18 | "easy": null,
19 | "medium": null,
20 | "hard": null,
21 | "very-hard": null,
22 | "insane": null,
23 | "inhuman": null,
24 | "import": null,
25 | };
26 |
27 | var build_board = function(){
28 | /* Build the Sudoku board markup
29 |
30 | TODO: Hardcode the result
31 | */
32 | for(var r = 0; r < 9; ++r){
33 | var $row = $("
", {});
34 | for(var c = 0; c < 9; ++c){
35 | var $square = $(" | ", {});
36 | if(c % 3 == 2 && c != 8){
37 | $square.addClass("border-right");
38 | }
39 | $square.append(
40 | $("", {
41 | id: "row" + r + "-col" + c,
42 | class: "square",
43 | maxlength: "9",
44 | type: "text"
45 | })
46 | );
47 | $row.append($square);
48 | }
49 | if(r % 3 == 2 && r != 8){
50 | $row.addClass("border-bottom");
51 | }
52 | $(BOARD_SEL).append($row);
53 | }
54 | };
55 |
56 | var init_board = function(){
57 | /* Initialize board interactions
58 | */
59 | $(BOARD_SEL + " input.square").change(function(){
60 | /* Resize font size in each square depending on how many characters are
61 | in it.
62 | */
63 | var $square = $(this);
64 | var nr_digits = $square.val().length;
65 | var font_size = "40px";
66 | if(nr_digits === 3){
67 | font_size = "35px";
68 | } else if(nr_digits === 4){
69 | font_size = "25px";
70 | } else if(nr_digits === 5){
71 | font_size = "20px";
72 | } else if(nr_digits === 6){
73 | font_size = "17px";
74 | } else if(nr_digits === 7){
75 | font_size = "14px";
76 | } else if(nr_digits === 8){
77 | font_size = "13px";
78 | } else if(nr_digits >= 9){
79 | font_size = "11px";
80 | }
81 | $(this).css("font-size", font_size);
82 | });
83 | $(BOARD_SEL + " input.square").keyup(function(){
84 | /* Fire a change event on keyup, enforce digits
85 | */
86 | $(this).change();
87 | });
88 |
89 | };
90 |
91 | var init_tabs = function(){
92 | /* Initialize the Sudoku generator tabs
93 | */
94 | $(TABS_SEL + " a").click(function(e){
95 | e.preventDefault();
96 | var $t = $(this);
97 | var t_name = $t.attr("id");
98 |
99 | // Hide any error messages
100 | $(MESSAGE_SEL).hide();
101 |
102 | // If it's the import tab
103 | if(t_name === "import"){
104 | $(PUZZLE_CONTROLS_SEL).hide();
105 | $(IMPORT_CONTROLS_SEL).show();
106 |
107 | // Otherwise it's a normal difficulty tab
108 | } else {
109 | $(PUZZLE_CONTROLS_SEL).show();
110 | $(IMPORT_CONTROLS_SEL).hide();
111 | }
112 | show_puzzle(t_name);
113 | $t.tab('show');
114 | });
115 | };
116 |
117 | var init_controls = function(){
118 | /* Initialize the controls
119 | */
120 |
121 | // Puzzle controls
122 | $(PUZZLE_CONTROLS_SEL + " #refresh").click(function(e){
123 | /* Refresh the current puzzle
124 | */
125 | e.preventDefault();
126 | var tab_name = get_tab();
127 | if(tab_name !== "import"){
128 | show_puzzle(tab_name, true);
129 | }
130 | });
131 |
132 | // Import controls
133 | $(IMPORT_CONTROLS_SEL + " #import-string").change(function(){
134 | /* Update the board to reflect the import string
135 | */
136 | var import_val = $(this).val();
137 | var processed_board = "";
138 | for(var i = 0; i < 81; ++i){
139 | if(typeof import_val[i] !== "undefined" &&
140 | (sudoku._in(import_val[i], sudoku.DIGITS) ||
141 | import_val[i] === sudoku.BLANK_CHAR)){
142 | processed_board += import_val[i];
143 | } else {
144 | processed_board += sudoku.BLANK_CHAR;
145 | }
146 | }
147 | boards["import"] = sudoku.board_string_to_grid(processed_board);
148 | show_puzzle("import");
149 | });
150 | $(IMPORT_CONTROLS_SEL + " #import-string").keyup(function(){
151 | /* Fire a change event on keyup, enforce digits
152 | */
153 | $(this).change();
154 | });
155 |
156 | // Solver controls
157 | $(SOLVER_CONTROLS_SEL + " #solve").click(function(e){
158 | /* Solve the current puzzle
159 | */
160 | e.preventDefault();
161 | solve_puzzle(get_tab());
162 | });
163 |
164 | $(SOLVER_CONTROLS_SEL + " #get-candidates").click(function(e){
165 | /* Get candidates for the current puzzle
166 | */
167 | e.preventDefault();
168 | get_candidates(get_tab());
169 | });
170 | };
171 |
172 | var init_message = function(){
173 | /* Initialize the message bar
174 | */
175 |
176 | //Hide initially
177 | $(MESSAGE_SEL).hide();
178 | }
179 |
180 | var solve_puzzle = function(puzzle){
181 | /* Solve the specified puzzle and show it
182 | */
183 |
184 | // Solve only if it's a valid puzzle
185 | if(typeof boards[puzzle] !== "undefined"){
186 | display_puzzle(boards[puzzle], true);
187 |
188 | var error = false;
189 | try{
190 | var solved_board =
191 | sudoku.solve(sudoku.board_grid_to_string(boards[puzzle]));
192 | } catch(e) {
193 | error = true;
194 | }
195 |
196 | // Display the solved puzzle if solved successfully, display error if
197 | // unable to solve.
198 | if(solved_board && !error){
199 | display_puzzle(sudoku.board_string_to_grid(solved_board), true);
200 | $(MESSAGE_SEL).hide();
201 | } else {
202 | $(MESSAGE_SEL + " #text")
203 | .html("Unable to solve! "
204 | + "Check puzzle and try again.");
205 | $(MESSAGE_SEL).show();
206 | }
207 | }
208 | };
209 |
210 | var get_candidates = function(puzzle){
211 | /* Get the candidates for the specified puzzle and show it
212 | */
213 |
214 | // Get candidates only if it's a valid puzzle
215 | if(typeof boards[puzzle] !== "undefined"){
216 | display_puzzle(boards[puzzle], true);
217 |
218 | var error = false;
219 | try{
220 | var candidates =
221 | sudoku.get_candidates(
222 | sudoku.board_grid_to_string(boards[puzzle])
223 | );
224 | } catch(e) {
225 | error = true;
226 | }
227 |
228 | // Display the candidates if solved successfully, display error if
229 | // unable to solve.
230 | if(candidates && !error){
231 | display_puzzle(candidates, true);
232 | $(MESSAGE_SEL).hide();
233 | } else {
234 | $(MESSAGE_SEL + " #text")
235 | .html("Unable to display candidates! " +
236 | "Contradictions encountered. Check puzzle and try again.");
237 | $(MESSAGE_SEL).show();
238 | }
239 | }
240 | }
241 |
242 | var show_puzzle = function(puzzle, refresh){
243 | /* Show the puzzle of the specified puzzle. If the board has not been
244 | generated yet, generate a new one and save. Optionally, set `refresh` to
245 | force a refresh of the specified puzzle.
246 | */
247 |
248 | // default refresh to false
249 | refresh = refresh || false;
250 |
251 | // If not a valid puzzle, default -> "easy"
252 | if(typeof boards[puzzle] === "undefined"){
253 | puzzle = "easy";
254 | }
255 |
256 | // If the board at the specified puzzle doesn't exist yet, or `refresh`
257 | // is set, generate a new one
258 | if(boards[puzzle] === null || refresh){
259 | if(puzzle === "import"){
260 | boards[puzzle] = sudoku.board_string_to_grid(sudoku.BLANK_BOARD);
261 | } else {
262 | boards[puzzle] =
263 | sudoku.board_string_to_grid(sudoku.generate(puzzle));
264 | }
265 | }
266 |
267 | // Display the puzzle
268 | display_puzzle(boards[puzzle]);
269 | }
270 |
271 | var display_puzzle = function(board, highlight){
272 | /* Display a Sudoku puzzle on the board, optionally highlighting the new
273 | values, with green if `highlight` is set. Additionally do not disable the
274 | new value squares.
275 | */
276 | for(var r = 0; r < 9; ++r){
277 | for(var c = 0; c < 9; ++c){
278 | var $square = $(BOARD_SEL + " input#row" + r + "-col" + c);
279 | $square.removeClass("green-text");
280 | $square.attr("disabled", "disabled");
281 | if(board[r][c] != sudoku.BLANK_CHAR){
282 | var board_val = board[r][c];
283 | var square_val = $square.val();
284 | if(highlight && board_val != square_val){
285 | $square.addClass("green-text");
286 | }
287 | $square.val(board_val);
288 | } else {
289 | $square.val('');
290 | }
291 | // Fire off a change event on the square
292 | $square.change();
293 | }
294 | }
295 | };
296 |
297 | var get_tab = function(){
298 | /* Return the name of the currently-selected tab
299 | */
300 | return $(TABS_SEL + " li.active a").attr("id");
301 | };
302 |
303 | var click_tab = function(tab_name){
304 | /* Click the specified tab by name
305 | */
306 | $(TABS_SEL + " #" + tab_name).click();
307 | };
308 |
309 | // "Main" (document ready)
310 | $(function(){
311 | build_board();
312 | init_board();
313 | init_tabs();
314 | init_controls();
315 | init_message();
316 |
317 | // Initialize tooltips
318 | $("[rel='tooltip']").tooltip();
319 |
320 | // Start with generating an easy puzzle
321 | click_tab("easy");
322 |
323 | // Hide the loading screen, show the app
324 | $("#app-wrap").removeClass("hidden");
325 | $("#loading").addClass("hidden");
326 | });
--------------------------------------------------------------------------------
/demo/assets/css/bootstrap-responsive.min.css:
--------------------------------------------------------------------------------
1 | /*!
2 | * Bootstrap Responsive v2.2.2
3 | *
4 | * Copyright 2012 Twitter, Inc
5 | * Licensed under the Apache License v2.0
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Designed and built with all the love in the world @twitter by @mdo and @fat.
9 | */@-ms-viewport{width:device-width}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.hidden{display:none;visibility:hidden}.visible-phone{display:none!important}.visible-tablet{display:none!important}.hidden-desktop{display:none!important}.visible-desktop{display:inherit!important}@media(min-width:768px) and (max-width:979px){.hidden-desktop{display:inherit!important}.visible-desktop{display:none!important}.visible-tablet{display:inherit!important}.hidden-tablet{display:none!important}}@media(max-width:767px){.hidden-desktop{display:inherit!important}.visible-desktop{display:none!important}.visible-phone{display:inherit!important}.hidden-phone{display:none!important}}@media(min-width:1200px){.row{margin-left:-30px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:30px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:1170px}.span12{width:1170px}.span11{width:1070px}.span10{width:970px}.span9{width:870px}.span8{width:770px}.span7{width:670px}.span6{width:570px}.span5{width:470px}.span4{width:370px}.span3{width:270px}.span2{width:170px}.span1{width:70px}.offset12{margin-left:1230px}.offset11{margin-left:1130px}.offset10{margin-left:1030px}.offset9{margin-left:930px}.offset8{margin-left:830px}.offset7{margin-left:730px}.offset6{margin-left:630px}.offset5{margin-left:530px}.offset4{margin-left:430px}.offset3{margin-left:330px}.offset2{margin-left:230px}.offset1{margin-left:130px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.564102564102564%;*margin-left:2.5109110747408616%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.564102564102564%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.45299145299145%;*width:91.39979996362975%}.row-fluid .span10{width:82.90598290598291%;*width:82.8527914166212%}.row-fluid .span9{width:74.35897435897436%;*width:74.30578286961266%}.row-fluid .span8{width:65.81196581196582%;*width:65.75877432260411%}.row-fluid .span7{width:57.26495726495726%;*width:57.21176577559556%}.row-fluid .span6{width:48.717948717948715%;*width:48.664757228587014%}.row-fluid .span5{width:40.17094017094017%;*width:40.11774868157847%}.row-fluid .span4{width:31.623931623931625%;*width:31.570740134569924%}.row-fluid .span3{width:23.076923076923077%;*width:23.023731587561375%}.row-fluid .span2{width:14.52991452991453%;*width:14.476723040552828%}.row-fluid .span1{width:5.982905982905983%;*width:5.929714493544281%}.row-fluid .offset12{margin-left:105.12820512820512%;*margin-left:105.02182214948171%}.row-fluid .offset12:first-child{margin-left:102.56410256410257%;*margin-left:102.45771958537915%}.row-fluid .offset11{margin-left:96.58119658119658%;*margin-left:96.47481360247316%}.row-fluid .offset11:first-child{margin-left:94.01709401709402%;*margin-left:93.91071103837061%}.row-fluid .offset10{margin-left:88.03418803418803%;*margin-left:87.92780505546462%}.row-fluid .offset10:first-child{margin-left:85.47008547008548%;*margin-left:85.36370249136206%}.row-fluid .offset9{margin-left:79.48717948717949%;*margin-left:79.38079650845607%}.row-fluid .offset9:first-child{margin-left:76.92307692307693%;*margin-left:76.81669394435352%}.row-fluid .offset8{margin-left:70.94017094017094%;*margin-left:70.83378796144753%}.row-fluid .offset8:first-child{margin-left:68.37606837606839%;*margin-left:68.26968539734497%}.row-fluid .offset7{margin-left:62.393162393162385%;*margin-left:62.28677941443899%}.row-fluid .offset7:first-child{margin-left:59.82905982905982%;*margin-left:59.72267685033642%}.row-fluid .offset6{margin-left:53.84615384615384%;*margin-left:53.739770867430444%}.row-fluid .offset6:first-child{margin-left:51.28205128205128%;*margin-left:51.175668303327875%}.row-fluid .offset5{margin-left:45.299145299145295%;*margin-left:45.1927623204219%}.row-fluid .offset5:first-child{margin-left:42.73504273504273%;*margin-left:42.62865975631933%}.row-fluid .offset4{margin-left:36.75213675213675%;*margin-left:36.645753773413354%}.row-fluid .offset4:first-child{margin-left:34.18803418803419%;*margin-left:34.081651209310785%}.row-fluid .offset3{margin-left:28.205128205128204%;*margin-left:28.0987452264048%}.row-fluid .offset3:first-child{margin-left:25.641025641025642%;*margin-left:25.53464266230224%}.row-fluid .offset2{margin-left:19.65811965811966%;*margin-left:19.551736679396257%}.row-fluid .offset2:first-child{margin-left:17.094017094017094%;*margin-left:16.98763411529369%}.row-fluid .offset1{margin-left:11.11111111111111%;*margin-left:11.004728132387708%}.row-fluid .offset1:first-child{margin-left:8.547008547008547%;*margin-left:8.440625568285142%}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:30px}input.span12,textarea.span12,.uneditable-input.span12{width:1156px}input.span11,textarea.span11,.uneditable-input.span11{width:1056px}input.span10,textarea.span10,.uneditable-input.span10{width:956px}input.span9,textarea.span9,.uneditable-input.span9{width:856px}input.span8,textarea.span8,.uneditable-input.span8{width:756px}input.span7,textarea.span7,.uneditable-input.span7{width:656px}input.span6,textarea.span6,.uneditable-input.span6{width:556px}input.span5,textarea.span5,.uneditable-input.span5{width:456px}input.span4,textarea.span4,.uneditable-input.span4{width:356px}input.span3,textarea.span3,.uneditable-input.span3{width:256px}input.span2,textarea.span2,.uneditable-input.span2{width:156px}input.span1,textarea.span1,.uneditable-input.span1{width:56px}.thumbnails{margin-left:-30px}.thumbnails>li{margin-left:30px}.row-fluid .thumbnails{margin-left:0}}@media(min-width:768px) and (max-width:979px){.row{margin-left:-20px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:20px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:724px}.span12{width:724px}.span11{width:662px}.span10{width:600px}.span9{width:538px}.span8{width:476px}.span7{width:414px}.span6{width:352px}.span5{width:290px}.span4{width:228px}.span3{width:166px}.span2{width:104px}.span1{width:42px}.offset12{margin-left:764px}.offset11{margin-left:702px}.offset10{margin-left:640px}.offset9{margin-left:578px}.offset8{margin-left:516px}.offset7{margin-left:454px}.offset6{margin-left:392px}.offset5{margin-left:330px}.offset4{margin-left:268px}.offset3{margin-left:206px}.offset2{margin-left:144px}.offset1{margin-left:82px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.7624309392265194%;*margin-left:2.709239449864817%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.7624309392265194%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.43646408839778%;*width:91.38327259903608%}.row-fluid .span10{width:82.87292817679558%;*width:82.81973668743387%}.row-fluid .span9{width:74.30939226519337%;*width:74.25620077583166%}.row-fluid .span8{width:65.74585635359117%;*width:65.69266486422946%}.row-fluid .span7{width:57.18232044198895%;*width:57.12912895262725%}.row-fluid .span6{width:48.61878453038674%;*width:48.56559304102504%}.row-fluid .span5{width:40.05524861878453%;*width:40.00205712942283%}.row-fluid .span4{width:31.491712707182323%;*width:31.43852121782062%}.row-fluid .span3{width:22.92817679558011%;*width:22.87498530621841%}.row-fluid .span2{width:14.3646408839779%;*width:14.311449394616199%}.row-fluid .span1{width:5.801104972375691%;*width:5.747913483013988%}.row-fluid .offset12{margin-left:105.52486187845304%;*margin-left:105.41847889972962%}.row-fluid .offset12:first-child{margin-left:102.76243093922652%;*margin-left:102.6560479605031%}.row-fluid .offset11{margin-left:96.96132596685082%;*margin-left:96.8549429881274%}.row-fluid .offset11:first-child{margin-left:94.1988950276243%;*margin-left:94.09251204890089%}.row-fluid .offset10{margin-left:88.39779005524862%;*margin-left:88.2914070765252%}.row-fluid .offset10:first-child{margin-left:85.6353591160221%;*margin-left:85.52897613729868%}.row-fluid .offset9{margin-left:79.8342541436464%;*margin-left:79.72787116492299%}.row-fluid .offset9:first-child{margin-left:77.07182320441989%;*margin-left:76.96544022569647%}.row-fluid .offset8{margin-left:71.2707182320442%;*margin-left:71.16433525332079%}.row-fluid .offset8:first-child{margin-left:68.50828729281768%;*margin-left:68.40190431409427%}.row-fluid .offset7{margin-left:62.70718232044199%;*margin-left:62.600799341718584%}.row-fluid .offset7:first-child{margin-left:59.94475138121547%;*margin-left:59.838368402492065%}.row-fluid .offset6{margin-left:54.14364640883978%;*margin-left:54.037263430116376%}.row-fluid .offset6:first-child{margin-left:51.38121546961326%;*margin-left:51.27483249088986%}.row-fluid .offset5{margin-left:45.58011049723757%;*margin-left:45.47372751851417%}.row-fluid .offset5:first-child{margin-left:42.81767955801105%;*margin-left:42.71129657928765%}.row-fluid .offset4{margin-left:37.01657458563536%;*margin-left:36.91019160691196%}.row-fluid .offset4:first-child{margin-left:34.25414364640884%;*margin-left:34.14776066768544%}.row-fluid .offset3{margin-left:28.45303867403315%;*margin-left:28.346655695309746%}.row-fluid .offset3:first-child{margin-left:25.69060773480663%;*margin-left:25.584224756083227%}.row-fluid .offset2{margin-left:19.88950276243094%;*margin-left:19.783119783707537%}.row-fluid .offset2:first-child{margin-left:17.12707182320442%;*margin-left:17.02068884448102%}.row-fluid .offset1{margin-left:11.32596685082873%;*margin-left:11.219583872105325%}.row-fluid .offset1:first-child{margin-left:8.56353591160221%;*margin-left:8.457152932878806%}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:20px}input.span12,textarea.span12,.uneditable-input.span12{width:710px}input.span11,textarea.span11,.uneditable-input.span11{width:648px}input.span10,textarea.span10,.uneditable-input.span10{width:586px}input.span9,textarea.span9,.uneditable-input.span9{width:524px}input.span8,textarea.span8,.uneditable-input.span8{width:462px}input.span7,textarea.span7,.uneditable-input.span7{width:400px}input.span6,textarea.span6,.uneditable-input.span6{width:338px}input.span5,textarea.span5,.uneditable-input.span5{width:276px}input.span4,textarea.span4,.uneditable-input.span4{width:214px}input.span3,textarea.span3,.uneditable-input.span3{width:152px}input.span2,textarea.span2,.uneditable-input.span2{width:90px}input.span1,textarea.span1,.uneditable-input.span1{width:28px}}@media(max-width:767px){body{padding-right:20px;padding-left:20px}.navbar-fixed-top,.navbar-fixed-bottom,.navbar-static-top{margin-right:-20px;margin-left:-20px}.container-fluid{padding:0}.dl-horizontal dt{float:none;width:auto;clear:none;text-align:left}.dl-horizontal dd{margin-left:0}.container{width:auto}.row-fluid{width:100%}.row,.thumbnails{margin-left:0}.thumbnails>li{float:none;margin-left:0}[class*="span"],.uneditable-input[class*="span"],.row-fluid [class*="span"]{display:block;float:none;width:100%;margin-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.span12,.row-fluid .span12{width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="offset"]:first-child{margin-left:0}.input-large,.input-xlarge,.input-xxlarge,input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.input-prepend input,.input-append input,.input-prepend input[class*="span"],.input-append input[class*="span"]{display:inline-block;width:auto}.controls-row [class*="span"]+[class*="span"]{margin-left:0}.modal{position:fixed;top:20px;right:20px;left:20px;width:auto;margin:0}.modal.fade{top:-100px}.modal.fade.in{top:20px}}@media(max-width:480px){.nav-collapse{-webkit-transform:translate3d(0,0,0)}.page-header h1 small{display:block;line-height:20px}input[type="checkbox"],input[type="radio"]{border:1px solid #ccc}.form-horizontal .control-label{float:none;width:auto;padding-top:0;text-align:left}.form-horizontal .controls{margin-left:0}.form-horizontal .control-list{padding-top:0}.form-horizontal .form-actions{padding-right:10px;padding-left:10px}.media .pull-left,.media .pull-right{display:block;float:none;margin-bottom:10px}.media-object{margin-right:0;margin-left:0}.modal{top:10px;right:10px;left:10px}.modal-header .close{padding:10px;margin:-10px}.carousel-caption{position:static}}@media(max-width:979px){body{padding-top:0}.navbar-fixed-top,.navbar-fixed-bottom{position:static}.navbar-fixed-top{margin-bottom:20px}.navbar-fixed-bottom{margin-top:20px}.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding:5px}.navbar .container{width:auto;padding:0}.navbar .brand{padding-right:10px;padding-left:10px;margin:0 0 0 -5px}.nav-collapse{clear:both}.nav-collapse .nav{float:none;margin:0 0 10px}.nav-collapse .nav>li{float:none}.nav-collapse .nav>li>a{margin-bottom:2px}.nav-collapse .nav>.divider-vertical{display:none}.nav-collapse .nav .nav-header{color:#777;text-shadow:none}.nav-collapse .nav>li>a,.nav-collapse .dropdown-menu a{padding:9px 15px;font-weight:bold;color:#777;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.nav-collapse .btn{padding:4px 10px 4px;font-weight:normal;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.nav-collapse .dropdown-menu li+li a{margin-bottom:2px}.nav-collapse .nav>li>a:hover,.nav-collapse .dropdown-menu a:hover{background-color:#f2f2f2}.navbar-inverse .nav-collapse .nav>li>a,.navbar-inverse .nav-collapse .dropdown-menu a{color:#999}.navbar-inverse .nav-collapse .nav>li>a:hover,.navbar-inverse .nav-collapse .dropdown-menu a:hover{background-color:#111}.nav-collapse.in .btn-group{padding:0;margin-top:5px}.nav-collapse .dropdown-menu{position:static;top:auto;left:auto;display:none;float:none;max-width:none;padding:0;margin:0 15px;background-color:transparent;border:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.nav-collapse .open>.dropdown-menu{display:block}.nav-collapse .dropdown-menu:before,.nav-collapse .dropdown-menu:after{display:none}.nav-collapse .dropdown-menu .divider{display:none}.nav-collapse .nav>li>.dropdown-menu:before,.nav-collapse .nav>li>.dropdown-menu:after{display:none}.nav-collapse .navbar-form,.nav-collapse .navbar-search{float:none;padding:10px 15px;margin:10px 0;border-top:1px solid #f2f2f2;border-bottom:1px solid #f2f2f2;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1)}.navbar-inverse .nav-collapse .navbar-form,.navbar-inverse .nav-collapse .navbar-search{border-top-color:#111;border-bottom-color:#111}.navbar .nav-collapse .nav.pull-right{float:none;margin-left:0}.nav-collapse,.nav-collapse.collapse{height:0;overflow:hidden}.navbar .btn-navbar{display:block}.navbar-static .navbar-inner{padding-right:10px;padding-left:10px}}@media(min-width:980px){.nav-collapse.collapse{height:auto!important;overflow:visible!important}}
10 |
--------------------------------------------------------------------------------
/test/tests.js:
--------------------------------------------------------------------------------
1 | /* Unit tests for sudoku.js
2 | */
3 |
4 | // 95 "difficult" puzzles from http://magictour.free.fr/top95
5 | var TEST_PUZZLES = [
6 | "4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......",
7 | "52...6.........7.13...........4..8..6......5...........418.........3..2...87.....",
8 | "6.....8.3.4.7.................5.4.7.3..2.....1.6.......2.....5.....8.6......1....",
9 | "48.3............71.2.......7.5....6....2..8.............1.76...3.....4......5....",
10 | "....14....3....2...7..........9...3.6.1.............8.2.....1.4....5.6.....7.8...",
11 | "......52..8.4......3...9...5.1...6..2..7........3.....6...1..........7.4.......3.",
12 | "6.2.5.........3.4..........43...8....1....2........7..5..27...........81...6.....",
13 | ".524.........7.1..............8.2...3.....6...9.5.....1.6.3...........897........",
14 | "6.2.5.........4.3..........43...8....1....2........7..5..27...........81...6.....",
15 | ".923.........8.1...........1.7.4...........658.........6.5.2...4.....7.....9.....",
16 | "6..3.2....5.....1..........7.26............543.........8.15........4.2........7..",
17 | ".6.5.1.9.1...9..539....7....4.8...7.......5.8.817.5.3.....5.2............76..8...",
18 | "..5...987.4..5...1..7......2...48....9.1.....6..2.....3..6..2.......9.7.......5..",
19 | "3.6.7...........518.........1.4.5...7.....6.....2......2.....4.....8.3.....5.....",
20 | "1.....3.8.7.4..............2.3.1...........958.........5.6...7.....8.2...4.......",
21 | "6..3.2....4.....1..........7.26............543.........8.15........4.2........7..",
22 | "....3..9....2....1.5.9..............1.2.8.4.6.8.5...2..75......4.1..6..3.....4.6.",
23 | "45.....3....8.1....9...........5..9.2..7.....8.........1..4..........7.2...6..8..",
24 | ".237....68...6.59.9.....7......4.97.3.7.96..2.........5..47.........2....8.......",
25 | "..84...3....3.....9....157479...8........7..514.....2...9.6...2.5....4......9..56",
26 | ".98.1....2......6.............3.2.5..84.........6.........4.8.93..5...........1..",
27 | "..247..58..............1.4.....2...9528.9.4....9...1.........3.3....75..685..2...",
28 | "4.....8.5.3..........7......2.....6.....5.4......1.......6.3.7.5..2.....1.9......",
29 | ".2.3......63.....58.......15....9.3....7........1....8.879..26......6.7...6..7..4",
30 | "1.....7.9.4...72..8.........7..1..6.3.......5.6..4..2.........8..53...7.7.2....46",
31 | "4.....3.....8.2......7........1...8734.......6........5...6........1.4...82......",
32 | ".......71.2.8........4.3...7...6..5....2..3..9........6...7.....8....4......5....",
33 | "6..3.2....4.....8..........7.26............543.........8.15........8.2........7..",
34 | ".47.8...1............6..7..6....357......5....1..6....28..4.....9.1...4.....2.69.",
35 | "......8.17..2........5.6......7...5..1....3...8.......5......2..4..8....6...3....",
36 | "38.6.......9.......2..3.51......5....3..1..6....4......17.5..8.......9.......7.32",
37 | "...5...........5.697.....2...48.2...25.1...3..8..3.........4.7..13.5..9..2...31..",
38 | ".2.......3.5.62..9.68...3...5..........64.8.2..47..9....3.....1.....6...17.43....",
39 | ".8..4....3......1........2...5...4.69..1..8..2...........3.9....6....5.....2.....",
40 | "..8.9.1...6.5...2......6....3.1.7.5.........9..4...3...5....2...7...3.8.2..7....4",
41 | "4.....5.8.3..........7......2.....6.....5.8......1.......6.3.7.5..2.....1.8......",
42 | "1.....3.8.6.4..............2.3.1...........958.........5.6...7.....8.2...4.......",
43 | "1....6.8..64..........4...7....9.6...7.4..5..5...7.1...5....32.3....8...4........",
44 | "249.6...3.3....2..8.......5.....6......2......1..4.82..9.5..7....4.....1.7...3...",
45 | "...8....9.873...4.6..7.......85..97...........43..75.......3....3...145.4....2..1",
46 | "...5.1....9....8...6.......4.1..........7..9........3.8.....1.5...2..4.....36....",
47 | "......8.16..2........7.5......6...2..1....3...8.......2......7..3..8....5...4....",
48 | ".476...5.8.3.....2.....9......8.5..6...1.....6.24......78...51...6....4..9...4..7",
49 | ".....7.95.....1...86..2.....2..73..85......6...3..49..3.5...41724................",
50 | ".4.5.....8...9..3..76.2.....146..........9..7.....36....1..4.5..6......3..71..2..",
51 | ".834.........7..5...........4.1.8..........27...3.....2.6.5....5.....8........1..",
52 | "..9.....3.....9...7.....5.6..65..4.....3......28......3..75.6..6...........12.3.8",
53 | ".26.39......6....19.....7.......4..9.5....2....85.....3..2..9..4....762.........4",
54 | "2.3.8....8..7...........1...6.5.7...4......3....1............82.5....6...1.......",
55 | "6..3.2....1.....5..........7.26............843.........8.15........8.2........7..",
56 | "1.....9...64..1.7..7..4.......3.....3.89..5....7....2.....6.7.9.....4.1....129.3.",
57 | ".........9......84.623...5....6...453...1...6...9...7....1.....4.5..2....3.8....9",
58 | ".2....5938..5..46.94..6...8..2.3.....6..8.73.7..2.........4.38..7....6..........5",
59 | "9.4..5...25.6..1..31......8.7...9...4..26......147....7.......2...3..8.6.4.....9.",
60 | "...52.....9...3..4......7...1.....4..8..453..6...1...87.2........8....32.4..8..1.",
61 | "53..2.9...24.3..5...9..........1.827...7.........981.............64....91.2.5.43.",
62 | "1....786...7..8.1.8..2....9........24...1......9..5...6.8..........5.9.......93.4",
63 | "....5...11......7..6.....8......4.....9.1.3.....596.2..8..62..7..7......3.5.7.2..",
64 | ".47.2....8....1....3....9.2.....5...6..81..5.....4.....7....3.4...9...1.4..27.8..",
65 | "......94.....9...53....5.7..8.4..1..463...........7.8.8..7.....7......28.5.26....",
66 | ".2......6....41.....78....1......7....37.....6..412....1..74..5..8.5..7......39..",
67 | "1.....3.8.6.4..............2.3.1...........758.........7.5...6.....8.2...4.......",
68 | "2....1.9..1..3.7..9..8...2.......85..6.4.........7...3.2.3...6....5.....1.9...2.5",
69 | "..7..8.....6.2.3...3......9.1..5..6.....1.....7.9....2........4.83..4...26....51.",
70 | "...36....85.......9.4..8........68.........17..9..45...1.5...6.4....9..2.....3...",
71 | "34.6.......7.......2..8.57......5....7..1..2....4......36.2..1.......9.......7.82",
72 | "......4.18..2........6.7......8...6..4....3...1.......6......2..5..1....7...3....",
73 | ".4..5..67...1...4....2.....1..8..3........2...6...........4..5.3.....8..2........",
74 | ".......4...2..4..1.7..5..9...3..7....4..6....6..1..8...2....1..85.9...6.....8...3",
75 | "8..7....4.5....6............3.97...8....43..5....2.9....6......2...6...7.71..83.2",
76 | ".8...4.5....7..3............1..85...6.....2......4....3.26............417........",
77 | "....7..8...6...5...2...3.61.1...7..2..8..534.2..9.......2......58...6.3.4...1....",
78 | "......8.16..2........7.5......6...2..1....3...8.......2......7..4..8....5...3....",
79 | ".2..........6....3.74.8.........3..2.8..4..1.6..5.........1.78.5....9..........4.",
80 | ".52..68.......7.2.......6....48..9..2..41......1.....8..61..38.....9...63..6..1.9",
81 | "....1.78.5....9..........4..2..........6....3.74.8.........3..2.8..4..1.6..5.....",
82 | "1.......3.6.3..7...7...5..121.7...9...7........8.1..2....8.64....9.2..6....4.....",
83 | "4...7.1....19.46.5.....1......7....2..2.3....847..6....14...8.6.2....3..6...9....",
84 | "......8.17..2........5.6......7...5..1....3...8.......5......2..3..8....6...4....",
85 | "963......1....8......2.5....4.8......1....7......3..257......3...9.2.4.7......9..",
86 | "15.3......7..4.2....4.72.....8.........9..1.8.1..8.79......38...........6....7423",
87 | "..........5724...98....947...9..3...5..9..12...3.1.9...6....25....56.....7......6",
88 | "....75....1..2.....4...3...5.....3.2...8...1.......6.....1..48.2........7........",
89 | "6.....7.3.4.8.................5.4.8.7..2.....1.3.......2.....5.....7.9......1....",
90 | "....6...4..6.3....1..4..5.77.....8.5...8.....6.8....9...2.9....4....32....97..1..",
91 | ".32.....58..3.....9.428...1...4...39...6...5.....1.....2...67.8.....4....95....6.",
92 | "...5.3.......6.7..5.8....1636..2.......4.1.......3...567....2.8..4.7.......2..5..",
93 | ".5.3.7.4.1.........3.......5.8.3.61....8..5.9.6..1........4...6...6927....2...9..",
94 | "..5..8..18......9.......78....4.....64....9......53..2.6.........138..5....9.714.",
95 | "..........72.6.1....51...82.8...13..4.........37.9..1.....238..5.4..9.........79.",
96 | "...658.....4......12............96.7...3..5....2.8...3..19..8..3.6.....4....473..",
97 | ".2.3.......6..8.9.83.5........2...8.7.9..5........6..4.......1...1...4.22..7..8.9",
98 | ".5..9....1.....6.....3.8.....8.4...9514.......3....2..........4.8...6..77..15..6.",
99 | ".....2.......7...17..3...9.8..7......2.89.6...13..6....9..5.824.....891..........",
100 | "3...8.......7....51..............36...2..4....7...........6.13..452...........8.."
101 | ]
102 |
103 |
104 | // Solve
105 | // =====
106 | module('Solve');
107 |
108 | test("Solve", function(){
109 | var puz1 = [
110 | "52...6.........7.13...........4..8..6......5...........418.........3."+
111 | ".2...87.....",
112 | "527316489896542731314987562172453896689271354453698217941825673765134"+
113 | "928238769145"
114 | ]
115 | var puz2 = [
116 | "6.....8.3.4.7.................5.4.7.3..2.....1.6.......2.....5.....8."+
117 | "6......1....",
118 | "617459823248736915539128467982564371374291586156873294823647159791385"+
119 | "642465912738"
120 | ]
121 | var puz3 = [
122 | ".........9......84.623...5....6...453...1...6...9...7....1.....4.5..2"+
123 | "....3.8....9",
124 | "174589362953261784862347951219673845387415296546928173628194537495732"+
125 | "618731856429"
126 | ]
127 | var puz_unsolvable =
128 | ".........9......84.623...5....6...453...1...6...9...7....1.....4.5..2"+
129 | "....3.8...99";
130 | var puz_unsolvable2 = "5168497323.46.2...5.97...65135.6.9.7472591..696837."+
131 | ".5.253186.746842.75..791.5.6.8";
132 | var puz_too_big =
133 | ".........9......84.623...5....6...453...1...6...9...7....1.....4.5..2"+
134 | "....3.8....91";
135 | var puz_invalid_chars =
136 | ".........9......84.623...5....6...453...1...6...9...7....1.....4.5..2"+
137 | "....3.8..!.9";
138 |
139 | // Solve some hard puzzles with known answers
140 | ok(sudoku.solve(puz1[0]) === puz1[1], puz1[0] + " -> " + puz1[1]);
141 | ok(sudoku.solve(puz2[0]) === puz2[1], puz2[0] + " -> " + puz2[1]);
142 | ok(sudoku.solve(puz3[0]) === puz3[1], puz3[0] + " -> " + puz3[1]);
143 |
144 | // Solve all 95 difficult puzzles from above without any errors
145 | for(var i in TEST_PUZZLES){
146 | ok(sudoku.solve(TEST_PUZZLES[i]));
147 | }
148 |
149 | // Try to solve unsolvable puzzles
150 | ok(!sudoku.solve(puz_unsolvable), "Unsolvable");
151 | ok(!sudoku.solve(puz_unsolvable2), "Unsolvable 2");
152 |
153 | // Board too big
154 | throws(function(){sudoku.solve(puz_too_big)}, "Invalid board size");
155 |
156 | // Board has invalid character
157 | throws(function(){sudoku.solve(puz_invalid_chars)}, "Invalid characters");
158 | });
159 |
160 | test("Get candidates map", function(){
161 | var puz =
162 | "4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.."+
163 | "...1.4......";
164 | var puz_candidates = {
165 | "A1": "4", "A2": "1679", "A3": "12679", "A4": "139", "A5": "2369",
166 | "A6": "269", "A7": "8", "A8": "1239", "A9": "5", "B1": "26789",
167 | "B2": "3", "B3": "1256789", "B4": "14589", "B5": "24569",
168 | "B6": "245689", "B7": "12679", "B8": "1249", "B9": "124679",
169 | "C1": "2689", "C2": "15689", "C3": "125689", "C4": "7", "C5": "234569",
170 | "C6": "245689", "C7": "12369", "C8": "12349", "C9": "123469",
171 | "D1": "3789", "D2": "2", "D3": "15789", "D4": "3459", "D5": "34579",
172 | "D6": "4579", "D7": "13579", "D8": "6", "D9": "13789", "E1": "3679",
173 | "E2": "15679", "E3": "15679", "E4": "359", "E5": "8", "E6": "25679",
174 | "E7": "4", "E8": "12359", "E9": "12379", "F1": "36789", "F2": "4",
175 | "F3": "56789", "F4": "359", "F5": "1", "F6": "25679", "F7": "23579",
176 | "F8": "23589", "F9": "23789", "G1": "289", "G2": "89", "G3": "289",
177 | "G4": "6", "G5": "459", "G6": "3", "G7": "1259", "G8": "7",
178 | "G9": "12489",
179 | "H1": "5", "H2": "6789", "H3": "3", "H4": "2", "H5": "479", "H6": "1",
180 | "H7": "69", "H8": "489", "H9": "4689", "I1": "1", "I2": "6789",
181 | "I3": "4", "I4": "589", "I5": "579", "I6": "5789", "I7": "23569",
182 | "I8": "23589", "I9": "23689"
183 | }
184 | var puz_too_big =
185 | ".........9......84.623...5....6...453...1...6...9...7....1.....4.5..2"+
186 | "....3.8....91";
187 | var puz_invalid_chars =
188 | ".........9......84.623...5....6...453...1...6...9...7....1.....4.5..2"+
189 | "....3.8..!.9";
190 |
191 | // Get candidates for puzzle
192 | deepEqual(sudoku._get_candidates_map(puz), puz_candidates, puz);
193 |
194 | // Board too big
195 | throws(function(){sudoku._get_candidates_map(puz_too_big)},
196 | "Invalid board size");
197 |
198 | // Board has invalid character
199 | throws(function(){sudoku._get_candidates_map(puz_invalid_chars)},
200 | "Invalid characters");
201 | });
202 |
203 | test("Get candidates", function(){
204 | deepEqual(
205 | sudoku.get_candidates(
206 | "4.25..389....4.265..523.147..1652.7.6..1945322543876915....3.1....4..9.....8....3"
207 | ),[
208 | ["4","167","2","5","167","16","3","8","9"],
209 | ["13789","13789","3789","79","4","189","2","6","5"],
210 | ["89","689","5","2","3","689","1","4","7"],
211 | ["389","389","1","6","5","2","48","7","48"],
212 | ["6","78","78","1","9","4","5","3","2"],
213 | ["2","5","4","3","8","7","6","9","1"],
214 | ["5","246789","6789","79","267","3","478","1","468"],
215 | ["1378","123678","3678","4","1267","156","9","25","68"],
216 | ["179","124679","679","8","1267","1569","47","25","3"]
217 | ])
218 | });
219 |
220 | // Square relationships
221 | // ====================
222 |
223 | module("Square relationships");
224 |
225 | test("Get square -> vals map", function(){
226 | var puz =
227 | "4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.."+
228 | "...1.4......";
229 |
230 | deepEqual(sudoku._get_square_vals_map(puz), {
231 | "A1": "4", "A2": ".", "A3": ".", "A4": ".", "A5": ".", "A6": ".",
232 | "A7": "8", "A8": ".", "A9": "5", "B1": ".", "B2": "3", "B3": ".",
233 | "B4": ".", "B5": ".", "B6": ".", "B7": ".", "B8": ".", "B9": ".",
234 | "C1": ".", "C2": ".", "C3": ".", "C4": "7", "C5": ".", "C6": ".",
235 | "C7": ".", "C8": ".", "C9": ".", "D1": ".", "D2": "2", "D3": ".",
236 | "D4": ".", "D5": ".", "D6": ".", "D7": ".", "D8": "6", "D9": ".",
237 | "E1": ".", "E2": ".", "E3": ".", "E4": ".", "E5": "8", "E6": ".",
238 | "E7": "4", "E8": ".", "E9": ".", "F1": ".", "F2": ".", "F3": ".",
239 | "F4": ".", "F5": "1", "F6": ".", "F7": ".", "F8": ".", "F9": ".",
240 | "G1": ".", "G2": ".", "G3": ".", "G4": "6", "G5": ".", "G6": "3",
241 | "G7": ".", "G8": "7", "G9": ".", "H1": "5", "H2": ".", "H3": ".",
242 | "H4": "2", "H5": ".", "H6": ".", "H7": ".", "H8": ".", "H9": ".",
243 | "I1": "1", "I2": ".", "I3": "4", "I4": ".", "I5": ".", "I6": ".",
244 | "I7": ".", "I8": ".", "I9": "."
245 | }, "Testing with medium puzzle");
246 |
247 | throws(function(){sudoku._get_square_vals_map("")},
248 | "Size squares/puzzle size mismatch")
249 | });
250 |
251 | test("Get square -> units map", function(){
252 | var rows = "ABCDEFGHI";
253 | var cols = "123456789";
254 | var squares = sudoku._cross(rows, cols);
255 | var units = sudoku._get_all_units(rows, cols);
256 | var square_units_map = sudoku._get_square_units_map(squares, units);
257 |
258 | // Check units for A1
259 | deepEqual(square_units_map["A1"], [
260 | ["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"],
261 | ["A1", "B1", "C1", "D1", "E1", "F1", "G1", "H1", "I1"],
262 | ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"]
263 | ], "Units for A1");
264 |
265 | // Check units for E5
266 | deepEqual(square_units_map["E5"], [
267 | ["E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9"],
268 | ["A5", "B5", "C5", "D5", "E5", "F5", "G5", "H5", "I5"],
269 | ["D4", "D5", "D6", "E4", "E5", "E6", "F4", "F5", "F6"]
270 | ], "Units for E5");
271 | });
272 |
273 | test("Get square -> peers map", function(){
274 | var rows = "ABCDEFGHI";
275 | var cols = "123456789";
276 | var squares = sudoku._cross(rows, cols);
277 | var units = sudoku._get_all_units(rows, cols);
278 | var square_units_map = sudoku._get_square_units_map(squares, units);
279 | var square_peers_map = sudoku._get_square_peers_map(squares,
280 | square_units_map);
281 |
282 | // Check peers for A1
283 | deepEqual(square_peers_map["A1"], [
284 | "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "B1", "C1", "D1", "E1",
285 | "F1", "G1", "H1", "I1", "B2", "B3", "C2", "C3"],
286 | "Peers for A1");
287 |
288 | // Check peers for C2
289 | deepEqual(square_peers_map["C2"], [
290 | "C1", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "A2", "B2", "D2", "E2",
291 | "F2", "G2", "H2", "I2", "A1", "A3", "B1", "B3"],
292 | "Peers for C2");
293 | });
294 |
295 | test("Get all units", function(){
296 | var rows = "ABCDEFGHI";
297 | var cols = "123456789";
298 | var all_units = sudoku._get_all_units(rows, cols);
299 |
300 | // Make sure we have exactly 27 units (9 rows + 9 columns + 9 boxes)
301 | equal(all_units.length, 27, "27 units");
302 |
303 | // Look for the first row unit
304 | deepEqual(all_units[0],
305 | ["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"],
306 | "First row unit")
307 |
308 | // Look for the first col unit
309 | deepEqual(all_units[9],
310 | ["A1", "B1", "C1", "D1", "E1", "F1", "G1", "H1", "I1"],
311 | "First col unit")
312 |
313 | // Look for the first box unit
314 | deepEqual(all_units[18],
315 | ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"],
316 | "First box unit")
317 | });
318 |
319 |
320 | // Conversions
321 | // ===========
322 | module("Conversions");
323 |
324 | test("Board string -> grid", function(){
325 | var board1 = ".5.1972.8.9.2651.7217483596.4.3..7.9.3.7.98...796..32.981536472325974681764812953";
326 | var board2 = ".1.872.4..47695....651437..4217.8.3..7.2.4...58.9.12746583294171924873..734516...";
327 | var board3 = "23.94.67.8..3259149..76.32.1.....7925.321.4864..68.5317..1....96598721433...9...7";
328 |
329 | deepEqual(sudoku.board_string_to_grid(board1), [
330 | [".","5",".","1","9","7","2",".","8"],
331 | [".","9",".","2","6","5","1",".","7"],
332 | ["2","1","7","4","8","3","5","9","6"],
333 | [".","4",".","3",".",".","7",".","9"],
334 | [".","3",".","7",".","9","8",".","."],
335 | [".","7","9","6",".",".","3","2","."],
336 | ["9","8","1","5","3","6","4","7","2"],
337 | ["3","2","5","9","7","4","6","8","1"],
338 | ["7","6","4","8","1","2","9","5","3"]
339 | ]);
340 | deepEqual(sudoku.board_string_to_grid(board2), [
341 | [".","1",".","8","7","2",".","4","."],
342 | [".","4","7","6","9","5",".",".","."],
343 | [".","6","5","1","4","3","7",".","."],
344 | ["4","2","1","7",".","8",".","3","."],
345 | [".","7",".","2",".","4",".",".","."],
346 | ["5","8",".","9",".","1","2","7","4"],
347 | ["6","5","8","3","2","9","4","1","7"],
348 | ["1","9","2","4","8","7","3",".","."],
349 | ["7","3","4","5","1","6",".",".","."]
350 | ]);
351 | deepEqual(sudoku.board_string_to_grid(board3), [
352 | ["2","3",".","9","4",".","6","7","."],
353 | ["8",".",".","3","2","5","9","1","4"],
354 | ["9",".",".","7","6",".","3","2","."],
355 | ["1",".",".",".",".",".","7","9","2"],
356 | ["5",".","3","2","1",".","4","8","6"],
357 | ["4",".",".","6","8",".","5","3","1"],
358 | ["7",".",".","1",".",".",".",".","9"],
359 | ["6","5","9","8","7","2","1","4","3"],
360 | ["3",".",".",".","9",".",".",".","7"]
361 | ]);
362 | });
363 |
364 | test("Board grid -> string", function(){
365 | var grid1 = [
366 | [".","5",".","1","9","7","2",".","8"],
367 | [".","9",".","2","6","5","1",".","7"],
368 | ["2","1","7","4","8","3","5","9","6"],
369 | [".","4",".","3",".",".","7",".","9"],
370 | [".","3",".","7",".","9","8",".","."],
371 | [".","7","9","6",".",".","3","2","."],
372 | ["9","8","1","5","3","6","4","7","2"],
373 | ["3","2","5","9","7","4","6","8","1"],
374 | ["7","6","4","8","1","2","9","5","3"]
375 | ];
376 | var grid2 = [
377 | [".","1",".","8","7","2",".","4","."],
378 | [".","4","7","6","9","5",".",".","."],
379 | [".","6","5","1","4","3","7",".","."],
380 | ["4","2","1","7",".","8",".","3","."],
381 | [".","7",".","2",".","4",".",".","."],
382 | ["5","8",".","9",".","1","2","7","4"],
383 | ["6","5","8","3","2","9","4","1","7"],
384 | ["1","9","2","4","8","7","3",".","."],
385 | ["7","3","4","5","1","6",".",".","."]
386 | ];
387 | var grid3 = [
388 | ["2","3",".","9","4",".","6","7","."],
389 | ["8",".",".","3","2","5","9","1","4"],
390 | ["9",".",".","7","6",".","3","2","."],
391 | ["1",".",".",".",".",".","7","9","2"],
392 | ["5",".","3","2","1",".","4","8","6"],
393 | ["4",".",".","6","8",".","5","3","1"],
394 | ["7",".",".","1",".",".",".",".","9"],
395 | ["6","5","9","8","7","2","1","4","3"],
396 | ["3",".",".",".","9",".",".",".","7"]
397 | ];
398 |
399 | deepEqual(sudoku.board_grid_to_string(grid1),
400 | ".5.1972.8.9.2651.7217483596.4.3..7.9.3.7.98...796..32.981536472325974681764812953"
401 | );
402 | deepEqual(sudoku.board_grid_to_string(grid2),
403 | ".1.872.4..47695....651437..4217.8.3..7.2.4...58.9.12746583294171924873..734516..."
404 | );
405 | deepEqual(sudoku.board_grid_to_string(grid3),
406 | "23.94.67.8..3259149..76.32.1.....7925.321.4864..68.5317..1....96598721433...9...7"
407 | );
408 | });
409 |
410 | test("Integration", function(){
411 | for(var i = 0; i < 10; ++i){
412 | var board = sudoku.generate();
413 | var board_grid = sudoku.board_string_to_grid(board);
414 | var board_string = sudoku.board_grid_to_string(board_grid);
415 |
416 | ok(board === board_string);
417 | }
418 | });
419 |
420 |
421 | // Utility
422 | // =======
423 | module("Utility");
424 |
425 | test("Validate board", function(){
426 | var report_empty = sudoku.validate_board();
427 | var report_invalid_size = sudoku.validate_board("123");
428 | var report_invalid_char = sudoku.validate_board(
429 | ".3.9564272..784136764231589327149658.4.56..73..637._14412893765.8.627"+
430 | "341673415892");
431 | var report_good = sudoku.validate_board(
432 | ".3.9564272..784136764231589327149658.4.56..73..637..14412893765.8.627"+
433 | "341673415892");
434 |
435 | ok(report_empty !== true);
436 | ok(report_invalid_size !== true);
437 | ok(report_invalid_char !== true);
438 | ok(report_good);
439 | });
440 |
441 | test("Cross product", function(){
442 |
443 | // Simple case
444 | deepEqual(sudoku._cross('a','1'), ["a1"], "Simple case");
445 |
446 | // Classic case
447 | deepEqual(
448 | sudoku._cross("abc", "123"),
449 | ["a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3"],
450 | "Classic case"
451 | );
452 |
453 | // Empty case
454 | deepEqual(sudoku._cross('',''), [], "Empty case");
455 |
456 | // Classic case with arrays
457 | deepEqual(
458 | sudoku._cross(['a', 'b', 'c'], [1, 2, 3]),
459 | ["a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3"],
460 | "Classic case with arrays"
461 | );
462 |
463 | // Mismatched size
464 | deepEqual(
465 | sudoku._cross(['a', 'b', 'c'], [1, 2]),
466 | ["a1", "a2", "b1", "b2", "c1", "c2"],
467 | "Mismatched size"
468 | );
469 |
470 | // Empty default
471 | deepEqual(sudoku._cross(), [], "Empty arrays");
472 | });
473 |
474 | test("_in", function(){
475 | var seq = [1, 2, 3];
476 | var seq_string = "abc";
477 |
478 | // Normal
479 | ok(sudoku._in(1, seq), "Normal use case");
480 | ok(!sudoku._in(0, seq), "Normal use case (not)");
481 |
482 | // String
483 | ok(sudoku._in('a', seq_string), "String");
484 | ok(!sudoku._in('z', seq_string), "String (not)");
485 | });
486 |
487 |
--------------------------------------------------------------------------------
/demo/assets/js/bootstrap.min.js:
--------------------------------------------------------------------------------
1 | /*!
2 | * Bootstrap.js by @fat & @mdo
3 | * Copyright 2012 Twitter, Inc.
4 | * http://www.apache.org/licenses/LICENSE-2.0.txt
5 | */
6 | !function($){"use strict";$(function(){$.support.transition=function(){var transitionEnd=function(){var name,el=document.createElement("bootstrap"),transEndEventNames={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(name in transEndEventNames)if(void 0!==el.style[name])return transEndEventNames[name]}();return transitionEnd&&{end:transitionEnd}}()})}(window.jQuery),!function($){"use strict";var dismiss='[data-dismiss="alert"]',Alert=function(el){$(el).on("click",dismiss,this.close)};Alert.prototype.close=function(e){function removeElement(){$parent.trigger("closed").remove()}var $parent,$this=$(this),selector=$this.attr("data-target");selector||(selector=$this.attr("href"),selector=selector&&selector.replace(/.*(?=#[^\s]*$)/,"")),$parent=$(selector),e&&e.preventDefault(),$parent.length||($parent=$this.hasClass("alert")?$this:$this.parent()),$parent.trigger(e=$.Event("close")),e.isDefaultPrevented()||($parent.removeClass("in"),$.support.transition&&$parent.hasClass("fade")?$parent.on($.support.transition.end,removeElement):removeElement())};var old=$.fn.alert;$.fn.alert=function(option){return this.each(function(){var $this=$(this),data=$this.data("alert");data||$this.data("alert",data=new Alert(this)),"string"==typeof option&&data[option].call($this)})},$.fn.alert.Constructor=Alert,$.fn.alert.noConflict=function(){return $.fn.alert=old,this},$(document).on("click.alert.data-api",dismiss,Alert.prototype.close)}(window.jQuery),!function($){"use strict";var Button=function(element,options){this.$element=$(element),this.options=$.extend({},$.fn.button.defaults,options)};Button.prototype.setState=function(state){var d="disabled",$el=this.$element,data=$el.data(),val=$el.is("input")?"val":"html";state+="Text",data.resetText||$el.data("resetText",$el[val]()),$el[val](data[state]||this.options[state]),setTimeout(function(){"loadingText"==state?$el.addClass(d).attr(d,d):$el.removeClass(d).removeAttr(d)},0)},Button.prototype.toggle=function(){var $parent=this.$element.closest('[data-toggle="buttons-radio"]');$parent&&$parent.find(".active").removeClass("active"),this.$element.toggleClass("active")};var old=$.fn.button;$.fn.button=function(option){return this.each(function(){var $this=$(this),data=$this.data("button"),options="object"==typeof option&&option;data||$this.data("button",data=new Button(this,options)),"toggle"==option?data.toggle():option&&data.setState(option)})},$.fn.button.defaults={loadingText:"loading..."},$.fn.button.Constructor=Button,$.fn.button.noConflict=function(){return $.fn.button=old,this},$(document).on("click.button.data-api","[data-toggle^=button]",function(e){var $btn=$(e.target);$btn.hasClass("btn")||($btn=$btn.closest(".btn")),$btn.button("toggle")})}(window.jQuery),!function($){"use strict";var Carousel=function(element,options){this.$element=$(element),this.options=options,"hover"==this.options.pause&&this.$element.on("mouseenter",$.proxy(this.pause,this)).on("mouseleave",$.proxy(this.cycle,this))};Carousel.prototype={cycle:function(e){return e||(this.paused=!1),this.options.interval&&!this.paused&&(this.interval=setInterval($.proxy(this.next,this),this.options.interval)),this},to:function(pos){var $active=this.$element.find(".item.active"),children=$active.parent().children(),activePos=children.index($active),that=this;if(!(pos>children.length-1||0>pos))return this.sliding?this.$element.one("slid",function(){that.to(pos)}):activePos==pos?this.pause().cycle():this.slide(pos>activePos?"next":"prev",$(children[pos]))},pause:function(e){return e||(this.paused=!0),this.$element.find(".next, .prev").length&&$.support.transition.end&&(this.$element.trigger($.support.transition.end),this.cycle()),clearInterval(this.interval),this.interval=null,this},next:function(){return this.sliding?void 0:this.slide("next")},prev:function(){return this.sliding?void 0:this.slide("prev")},slide:function(type,next){var e,$active=this.$element.find(".item.active"),$next=next||$active[type](),isCycling=this.interval,direction="next"==type?"left":"right",fallback="next"==type?"first":"last",that=this;if(this.sliding=!0,isCycling&&this.pause(),$next=$next.length?$next:this.$element.find(".item")[fallback](),e=$.Event("slide",{relatedTarget:$next[0]}),!$next.hasClass("active")){if($.support.transition&&this.$element.hasClass("slide")){if(this.$element.trigger(e),e.isDefaultPrevented())return;$next.addClass(type),$next[0].offsetWidth,$active.addClass(direction),$next.addClass(direction),this.$element.one($.support.transition.end,function(){$next.removeClass([type,direction].join(" ")).addClass("active"),$active.removeClass(["active",direction].join(" ")),that.sliding=!1,setTimeout(function(){that.$element.trigger("slid")},0)})}else{if(this.$element.trigger(e),e.isDefaultPrevented())return;$active.removeClass("active"),$next.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return isCycling&&this.cycle(),this}}};var old=$.fn.carousel;$.fn.carousel=function(option){return this.each(function(){var $this=$(this),data=$this.data("carousel"),options=$.extend({},$.fn.carousel.defaults,"object"==typeof option&&option),action="string"==typeof option?option:options.slide;data||$this.data("carousel",data=new Carousel(this,options)),"number"==typeof option?data.to(option):action?data[action]():options.interval&&data.cycle()})},$.fn.carousel.defaults={interval:5e3,pause:"hover"},$.fn.carousel.Constructor=Carousel,$.fn.carousel.noConflict=function(){return $.fn.carousel=old,this},$(document).on("click.carousel.data-api","[data-slide]",function(e){var href,$this=$(this),$target=$($this.attr("data-target")||(href=$this.attr("href"))&&href.replace(/.*(?=#[^\s]+$)/,"")),options=$.extend({},$target.data(),$this.data());$target.carousel(options),e.preventDefault()})}(window.jQuery),!function($){"use strict";var Collapse=function(element,options){this.$element=$(element),this.options=$.extend({},$.fn.collapse.defaults,options),this.options.parent&&(this.$parent=$(this.options.parent)),this.options.toggle&&this.toggle()};Collapse.prototype={constructor:Collapse,dimension:function(){var hasWidth=this.$element.hasClass("width");return hasWidth?"width":"height"},show:function(){var dimension,scroll,actives,hasData;if(!this.transitioning){if(dimension=this.dimension(),scroll=$.camelCase(["scroll",dimension].join("-")),actives=this.$parent&&this.$parent.find("> .accordion-group > .in"),actives&&actives.length){if(hasData=actives.data("collapse"),hasData&&hasData.transitioning)return;actives.collapse("hide"),hasData||actives.data("collapse",null)}this.$element[dimension](0),this.transition("addClass",$.Event("show"),"shown"),$.support.transition&&this.$element[dimension](this.$element[0][scroll])}},hide:function(){var dimension;this.transitioning||(dimension=this.dimension(),this.reset(this.$element[dimension]()),this.transition("removeClass",$.Event("hide"),"hidden"),this.$element[dimension](0))},reset:function(size){var dimension=this.dimension();return this.$element.removeClass("collapse")[dimension](size||"auto")[0].offsetWidth,this.$element[null!==size?"addClass":"removeClass"]("collapse"),this},transition:function(method,startEvent,completeEvent){var that=this,complete=function(){"show"==startEvent.type&&that.reset(),that.transitioning=0,that.$element.trigger(completeEvent)};this.$element.trigger(startEvent),startEvent.isDefaultPrevented()||(this.transitioning=1,this.$element[method]("in"),$.support.transition&&this.$element.hasClass("collapse")?this.$element.one($.support.transition.end,complete):complete())},toggle:function(){this[this.$element.hasClass("in")?"hide":"show"]()}};var old=$.fn.collapse;$.fn.collapse=function(option){return this.each(function(){var $this=$(this),data=$this.data("collapse"),options="object"==typeof option&&option;data||$this.data("collapse",data=new Collapse(this,options)),"string"==typeof option&&data[option]()})},$.fn.collapse.defaults={toggle:!0},$.fn.collapse.Constructor=Collapse,$.fn.collapse.noConflict=function(){return $.fn.collapse=old,this},$(document).on("click.collapse.data-api","[data-toggle=collapse]",function(e){var href,$this=$(this),target=$this.attr("data-target")||e.preventDefault()||(href=$this.attr("href"))&&href.replace(/.*(?=#[^\s]+$)/,""),option=$(target).data("collapse")?"toggle":$this.data();$this[$(target).hasClass("in")?"addClass":"removeClass"]("collapsed"),$(target).collapse(option)})}(window.jQuery),!function($){"use strict";function clearMenus(){$(toggle).each(function(){getParent($(this)).removeClass("open")})}function getParent($this){var $parent,selector=$this.attr("data-target");return selector||(selector=$this.attr("href"),selector=selector&&/#/.test(selector)&&selector.replace(/.*(?=#[^\s]*$)/,"")),$parent=$(selector),$parent.length||($parent=$this.parent()),$parent}var toggle="[data-toggle=dropdown]",Dropdown=function(element){var $el=$(element).on("click.dropdown.data-api",this.toggle);$("html").on("click.dropdown.data-api",function(){$el.parent().removeClass("open")})};Dropdown.prototype={constructor:Dropdown,toggle:function(){var $parent,isActive,$this=$(this);if(!$this.is(".disabled, :disabled"))return $parent=getParent($this),isActive=$parent.hasClass("open"),clearMenus(),isActive||$parent.toggleClass("open"),$this.focus(),!1},keydown:function(e){var $this,$items,$parent,isActive,index;if(/(38|40|27)/.test(e.keyCode)&&($this=$(this),e.preventDefault(),e.stopPropagation(),!$this.is(".disabled, :disabled"))){if($parent=getParent($this),isActive=$parent.hasClass("open"),!isActive||isActive&&27==e.keyCode)return $this.click();$items=$("[role=menu] li:not(.divider):visible a",$parent),$items.length&&(index=$items.index($items.filter(":focus")),38==e.keyCode&&index>0&&index--,40==e.keyCode&&$items.length-1>index&&index++,~index||(index=0),$items.eq(index).focus())}}};var old=$.fn.dropdown;$.fn.dropdown=function(option){return this.each(function(){var $this=$(this),data=$this.data("dropdown");data||$this.data("dropdown",data=new Dropdown(this)),"string"==typeof option&&data[option].call($this)})},$.fn.dropdown.Constructor=Dropdown,$.fn.dropdown.noConflict=function(){return $.fn.dropdown=old,this},$(document).on("click.dropdown.data-api touchstart.dropdown.data-api",clearMenus).on("click.dropdown touchstart.dropdown.data-api",".dropdown form",function(e){e.stopPropagation()}).on("touchstart.dropdown.data-api",".dropdown-menu",function(e){e.stopPropagation()}).on("click.dropdown.data-api touchstart.dropdown.data-api",toggle,Dropdown.prototype.toggle).on("keydown.dropdown.data-api touchstart.dropdown.data-api",toggle+", [role=menu]",Dropdown.prototype.keydown)}(window.jQuery),!function($){"use strict";var Modal=function(element,options){this.options=options,this.$element=$(element).delegate('[data-dismiss="modal"]',"click.dismiss.modal",$.proxy(this.hide,this)),this.options.remote&&this.$element.find(".modal-body").load(this.options.remote)};Modal.prototype={constructor:Modal,toggle:function(){return this[this.isShown?"hide":"show"]()},show:function(){var that=this,e=$.Event("show");this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.escape(),this.backdrop(function(){var transition=$.support.transition&&that.$element.hasClass("fade");that.$element.parent().length||that.$element.appendTo(document.body),that.$element.show(),transition&&that.$element[0].offsetWidth,that.$element.addClass("in").attr("aria-hidden",!1),that.enforceFocus(),transition?that.$element.one($.support.transition.end,function(){that.$element.focus().trigger("shown")}):that.$element.focus().trigger("shown")}))},hide:function(e){e&&e.preventDefault(),e=$.Event("hide"),this.$element.trigger(e),this.isShown&&!e.isDefaultPrevented()&&(this.isShown=!1,this.escape(),$(document).off("focusin.modal"),this.$element.removeClass("in").attr("aria-hidden",!0),$.support.transition&&this.$element.hasClass("fade")?this.hideWithTransition():this.hideModal())},enforceFocus:function(){var that=this;$(document).on("focusin.modal",function(e){that.$element[0]===e.target||that.$element.has(e.target).length||that.$element.focus()})},escape:function(){var that=this;this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.modal",function(e){27==e.which&&that.hide()}):this.isShown||this.$element.off("keyup.dismiss.modal")},hideWithTransition:function(){var that=this,timeout=setTimeout(function(){that.$element.off($.support.transition.end),that.hideModal()},500);this.$element.one($.support.transition.end,function(){clearTimeout(timeout),that.hideModal()})},hideModal:function(){this.$element.hide().trigger("hidden"),this.backdrop()},removeBackdrop:function(){this.$backdrop.remove(),this.$backdrop=null},backdrop:function(callback){var animate=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var doAnimate=$.support.transition&&animate;this.$backdrop=$('').appendTo(document.body),this.$backdrop.click("static"==this.options.backdrop?$.proxy(this.$element[0].focus,this.$element[0]):$.proxy(this.hide,this)),doAnimate&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),doAnimate?this.$backdrop.one($.support.transition.end,callback):callback()}else!this.isShown&&this.$backdrop?(this.$backdrop.removeClass("in"),$.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one($.support.transition.end,$.proxy(this.removeBackdrop,this)):this.removeBackdrop()):callback&&callback()}};var old=$.fn.modal;$.fn.modal=function(option){return this.each(function(){var $this=$(this),data=$this.data("modal"),options=$.extend({},$.fn.modal.defaults,$this.data(),"object"==typeof option&&option);data||$this.data("modal",data=new Modal(this,options)),"string"==typeof option?data[option]():options.show&&data.show()})},$.fn.modal.defaults={backdrop:!0,keyboard:!0,show:!0},$.fn.modal.Constructor=Modal,$.fn.modal.noConflict=function(){return $.fn.modal=old,this},$(document).on("click.modal.data-api",'[data-toggle="modal"]',function(e){var $this=$(this),href=$this.attr("href"),$target=$($this.attr("data-target")||href&&href.replace(/.*(?=#[^\s]+$)/,"")),option=$target.data("modal")?"toggle":$.extend({remote:!/#/.test(href)&&href},$target.data(),$this.data());e.preventDefault(),$target.modal(option).one("hide",function(){$this.focus()})})}(window.jQuery),!function($){"use strict";var Tooltip=function(element,options){this.init("tooltip",element,options)};Tooltip.prototype={constructor:Tooltip,init:function(type,element,options){var eventIn,eventOut;this.type=type,this.$element=$(element),this.options=this.getOptions(options),this.enabled=!0,"click"==this.options.trigger?this.$element.on("click."+this.type,this.options.selector,$.proxy(this.toggle,this)):"manual"!=this.options.trigger&&(eventIn="hover"==this.options.trigger?"mouseenter":"focus",eventOut="hover"==this.options.trigger?"mouseleave":"blur",this.$element.on(eventIn+"."+this.type,this.options.selector,$.proxy(this.enter,this)),this.$element.on(eventOut+"."+this.type,this.options.selector,$.proxy(this.leave,this))),this.options.selector?this._options=$.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},getOptions:function(options){return options=$.extend({},$.fn[this.type].defaults,options,this.$element.data()),options.delay&&"number"==typeof options.delay&&(options.delay={show:options.delay,hide:options.delay}),options},enter:function(e){var self=$(e.currentTarget)[this.type](this._options).data(this.type);return self.options.delay&&self.options.delay.show?(clearTimeout(this.timeout),self.hoverState="in",this.timeout=setTimeout(function(){"in"==self.hoverState&&self.show()},self.options.delay.show),void 0):self.show()},leave:function(e){var self=$(e.currentTarget)[this.type](this._options).data(this.type);return this.timeout&&clearTimeout(this.timeout),self.options.delay&&self.options.delay.hide?(self.hoverState="out",this.timeout=setTimeout(function(){"out"==self.hoverState&&self.hide()},self.options.delay.hide),void 0):self.hide()},show:function(){var $tip,inside,pos,actualWidth,actualHeight,placement,tp;if(this.hasContent()&&this.enabled){switch($tip=this.tip(),this.setContent(),this.options.animation&&$tip.addClass("fade"),placement="function"==typeof this.options.placement?this.options.placement.call(this,$tip[0],this.$element[0]):this.options.placement,inside=/in/.test(placement),$tip.detach().css({top:0,left:0,display:"block"}).insertAfter(this.$element),pos=this.getPosition(inside),actualWidth=$tip[0].offsetWidth,actualHeight=$tip[0].offsetHeight,inside?placement.split(" ")[1]:placement){case"bottom":tp={top:pos.top+pos.height,left:pos.left+pos.width/2-actualWidth/2};break;case"top":tp={top:pos.top-actualHeight,left:pos.left+pos.width/2-actualWidth/2};break;case"left":tp={top:pos.top+pos.height/2-actualHeight/2,left:pos.left-actualWidth};break;case"right":tp={top:pos.top+pos.height/2-actualHeight/2,left:pos.left+pos.width}}$tip.offset(tp).addClass(placement).addClass("in")}},setContent:function(){var $tip=this.tip(),title=this.getTitle();$tip.find(".tooltip-inner")[this.options.html?"html":"text"](title),$tip.removeClass("fade in top bottom left right")},hide:function(){function removeWithAnimation(){var timeout=setTimeout(function(){$tip.off($.support.transition.end).detach()},500);$tip.one($.support.transition.end,function(){clearTimeout(timeout),$tip.detach()})}var $tip=this.tip();return $tip.removeClass("in"),$.support.transition&&this.$tip.hasClass("fade")?removeWithAnimation():$tip.detach(),this},fixTitle:function(){var $e=this.$element;($e.attr("title")||"string"!=typeof $e.attr("data-original-title"))&&$e.attr("data-original-title",$e.attr("title")||"").removeAttr("title")},hasContent:function(){return this.getTitle()},getPosition:function(inside){return $.extend({},inside?{top:0,left:0}:this.$element.offset(),{width:this.$element[0].offsetWidth,height:this.$element[0].offsetHeight})},getTitle:function(){var title,$e=this.$element,o=this.options;return title=$e.attr("data-original-title")||("function"==typeof o.title?o.title.call($e[0]):o.title)},tip:function(){return this.$tip=this.$tip||$(this.options.template)},validate:function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},enable:function(){this.enabled=!0},disable:function(){this.enabled=!1},toggleEnabled:function(){this.enabled=!this.enabled},toggle:function(e){var self=$(e.currentTarget)[this.type](this._options).data(this.type);self[self.tip().hasClass("in")?"hide":"show"]()},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}};var old=$.fn.tooltip;$.fn.tooltip=function(option){return this.each(function(){var $this=$(this),data=$this.data("tooltip"),options="object"==typeof option&&option;data||$this.data("tooltip",data=new Tooltip(this,options)),"string"==typeof option&&data[option]()})},$.fn.tooltip.Constructor=Tooltip,$.fn.tooltip.defaults={animation:!0,placement:"top",selector:!1,template:'',trigger:"hover",title:"",delay:0,html:!1},$.fn.tooltip.noConflict=function(){return $.fn.tooltip=old,this}}(window.jQuery),!function($){"use strict";var Popover=function(element,options){this.init("popover",element,options)};Popover.prototype=$.extend({},$.fn.tooltip.Constructor.prototype,{constructor:Popover,setContent:function(){var $tip=this.tip(),title=this.getTitle(),content=this.getContent();$tip.find(".popover-title")[this.options.html?"html":"text"](title),$tip.find(".popover-content")[this.options.html?"html":"text"](content),$tip.removeClass("fade top bottom left right in")},hasContent:function(){return this.getTitle()||this.getContent()},getContent:function(){var content,$e=this.$element,o=this.options;return content=$e.attr("data-content")||("function"==typeof o.content?o.content.call($e[0]):o.content)},tip:function(){return this.$tip||(this.$tip=$(this.options.template)),this.$tip},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}});var old=$.fn.popover;$.fn.popover=function(option){return this.each(function(){var $this=$(this),data=$this.data("popover"),options="object"==typeof option&&option;data||$this.data("popover",data=new Popover(this,options)),"string"==typeof option&&data[option]()})},$.fn.popover.Constructor=Popover,$.fn.popover.defaults=$.extend({},$.fn.tooltip.defaults,{placement:"right",trigger:"click",content:"",template:''}),$.fn.popover.noConflict=function(){return $.fn.popover=old,this}}(window.jQuery),!function($){"use strict";function ScrollSpy(element,options){var href,process=$.proxy(this.process,this),$element=$(element).is("body")?$(window):$(element);this.options=$.extend({},$.fn.scrollspy.defaults,options),this.$scrollElement=$element.on("scroll.scroll-spy.data-api",process),this.selector=(this.options.target||(href=$(element).attr("href"))&&href.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.$body=$("body"),this.refresh(),this.process()}ScrollSpy.prototype={constructor:ScrollSpy,refresh:function(){var $targets,self=this;this.offsets=$([]),this.targets=$([]),$targets=this.$body.find(this.selector).map(function(){var $el=$(this),href=$el.data("target")||$el.attr("href"),$href=/^#\w/.test(href)&&$(href);return $href&&$href.length&&[[$href.position().top+self.$scrollElement.scrollTop(),href]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){self.offsets.push(this[0]),self.targets.push(this[1])})},process:function(){var i,scrollTop=this.$scrollElement.scrollTop()+this.options.offset,scrollHeight=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,maxScroll=scrollHeight-this.$scrollElement.height(),offsets=this.offsets,targets=this.targets,activeTarget=this.activeTarget;if(scrollTop>=maxScroll)return activeTarget!=(i=targets.last()[0])&&this.activate(i);for(i=offsets.length;i--;)activeTarget!=targets[i]&&scrollTop>=offsets[i]&&(!offsets[i+1]||offsets[i+1]>=scrollTop)&&this.activate(targets[i])},activate:function(target){var active,selector;this.activeTarget=target,$(this.selector).parent(".active").removeClass("active"),selector=this.selector+'[data-target="'+target+'"],'+this.selector+'[href="'+target+'"]',active=$(selector).parent("li").addClass("active"),active.parent(".dropdown-menu").length&&(active=active.closest("li.dropdown").addClass("active")),active.trigger("activate")}};var old=$.fn.scrollspy;$.fn.scrollspy=function(option){return this.each(function(){var $this=$(this),data=$this.data("scrollspy"),options="object"==typeof option&&option;data||$this.data("scrollspy",data=new ScrollSpy(this,options)),"string"==typeof option&&data[option]()})},$.fn.scrollspy.Constructor=ScrollSpy,$.fn.scrollspy.defaults={offset:10},$.fn.scrollspy.noConflict=function(){return $.fn.scrollspy=old,this},$(window).on("load",function(){$('[data-spy="scroll"]').each(function(){var $spy=$(this);$spy.scrollspy($spy.data())})})}(window.jQuery),!function($){"use strict";var Tab=function(element){this.element=$(element)};Tab.prototype={constructor:Tab,show:function(){var previous,$target,e,$this=this.element,$ul=$this.closest("ul:not(.dropdown-menu)"),selector=$this.attr("data-target");selector||(selector=$this.attr("href"),selector=selector&&selector.replace(/.*(?=#[^\s]*$)/,"")),$this.parent("li").hasClass("active")||(previous=$ul.find(".active:last a")[0],e=$.Event("show",{relatedTarget:previous}),$this.trigger(e),e.isDefaultPrevented()||($target=$(selector),this.activate($this.parent("li"),$ul),this.activate($target,$target.parent(),function(){$this.trigger({type:"shown",relatedTarget:previous})})))},activate:function(element,container,callback){function next(){$active.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),element.addClass("active"),transition?(element[0].offsetWidth,element.addClass("in")):element.removeClass("fade"),element.parent(".dropdown-menu")&&element.closest("li.dropdown").addClass("active"),callback&&callback()}var $active=container.find("> .active"),transition=callback&&$.support.transition&&$active.hasClass("fade");transition?$active.one($.support.transition.end,next):next(),$active.removeClass("in")}};var old=$.fn.tab;$.fn.tab=function(option){return this.each(function(){var $this=$(this),data=$this.data("tab");data||$this.data("tab",data=new Tab(this)),"string"==typeof option&&data[option]()})},$.fn.tab.Constructor=Tab,$.fn.tab.noConflict=function(){return $.fn.tab=old,this},$(document).on("click.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(e){e.preventDefault(),$(this).tab("show")})}(window.jQuery),!function($){"use strict";var Typeahead=function(element,options){this.$element=$(element),this.options=$.extend({},$.fn.typeahead.defaults,options),this.matcher=this.options.matcher||this.matcher,this.sorter=this.options.sorter||this.sorter,this.highlighter=this.options.highlighter||this.highlighter,this.updater=this.options.updater||this.updater,this.source=this.options.source,this.$menu=$(this.options.menu),this.shown=!1,this.listen()};Typeahead.prototype={constructor:Typeahead,select:function(){var val=this.$menu.find(".active").attr("data-value");return this.$element.val(this.updater(val)).change(),this.hide()},updater:function(item){return item},show:function(){var pos=$.extend({},this.$element.position(),{height:this.$element[0].offsetHeight});return this.$menu.insertAfter(this.$element).css({top:pos.top+pos.height,left:pos.left}).show(),this.shown=!0,this},hide:function(){return this.$menu.hide(),this.shown=!1,this},lookup:function(){var items;return this.query=this.$element.val(),!this.query||this.query.length"+match+""})},render:function(items){var that=this;return items=$(items).map(function(i,item){return i=$(that.options.item).attr("data-value",item),i.find("a").html(that.highlighter(item)),i[0]}),items.first().addClass("active"),this.$menu.html(items),this},next:function(){var active=this.$menu.find(".active").removeClass("active"),next=active.next();next.length||(next=$(this.$menu.find("li")[0])),next.addClass("active")},prev:function(){var active=this.$menu.find(".active").removeClass("active"),prev=active.prev();prev.length||(prev=this.$menu.find("li").last()),prev.addClass("active")},listen:function(){this.$element.on("blur",$.proxy(this.blur,this)).on("keypress",$.proxy(this.keypress,this)).on("keyup",$.proxy(this.keyup,this)),this.eventSupported("keydown")&&this.$element.on("keydown",$.proxy(this.keydown,this)),this.$menu.on("click",$.proxy(this.click,this)).on("mouseenter","li",$.proxy(this.mouseenter,this))},eventSupported:function(eventName){var isSupported=eventName in this.$element;return isSupported||(this.$element.setAttribute(eventName,"return;"),isSupported="function"==typeof this.$element[eventName]),isSupported},move:function(e){if(this.shown){switch(e.keyCode){case 9:case 13:case 27:e.preventDefault();break;case 38:e.preventDefault(),this.prev();break;case 40:e.preventDefault(),this.next()}e.stopPropagation()}},keydown:function(e){this.suppressKeyPressRepeat=~$.inArray(e.keyCode,[40,38,9,13,27]),this.move(e)},keypress:function(e){this.suppressKeyPressRepeat||this.move(e)},keyup:function(e){switch(e.keyCode){case 40:case 38:case 16:case 17:case 18:break;case 9:case 13:if(!this.shown)return;this.select();break;case 27:if(!this.shown)return;this.hide();break;default:this.lookup()}e.stopPropagation(),e.preventDefault()},blur:function(){var that=this;setTimeout(function(){that.hide()},150)},click:function(e){e.stopPropagation(),e.preventDefault(),this.select()},mouseenter:function(e){this.$menu.find(".active").removeClass("active"),$(e.currentTarget).addClass("active")}};var old=$.fn.typeahead;$.fn.typeahead=function(option){return this.each(function(){var $this=$(this),data=$this.data("typeahead"),options="object"==typeof option&&option;data||$this.data("typeahead",data=new Typeahead(this,options)),"string"==typeof option&&data[option]()})},$.fn.typeahead.defaults={source:[],items:8,menu:'',item:'',minLength:1},$.fn.typeahead.Constructor=Typeahead,$.fn.typeahead.noConflict=function(){return $.fn.typeahead=old,this},$(document).on("focus.typeahead.data-api",'[data-provide="typeahead"]',function(e){var $this=$(this);$this.data("typeahead")||(e.preventDefault(),$this.typeahead($this.data()))})}(window.jQuery),!function($){"use strict";var Affix=function(element,options){this.options=$.extend({},$.fn.affix.defaults,options),this.$window=$(window).on("scroll.affix.data-api",$.proxy(this.checkPosition,this)).on("click.affix.data-api",$.proxy(function(){setTimeout($.proxy(this.checkPosition,this),1)},this)),this.$element=$(element),this.checkPosition()};Affix.prototype.checkPosition=function(){if(this.$element.is(":visible")){var affix,scrollHeight=$(document).height(),scrollTop=this.$window.scrollTop(),position=this.$element.offset(),offset=this.options.offset,offsetBottom=offset.bottom,offsetTop=offset.top,reset="affix affix-top affix-bottom";"object"!=typeof offset&&(offsetBottom=offsetTop=offset),"function"==typeof offsetTop&&(offsetTop=offset.top()),"function"==typeof offsetBottom&&(offsetBottom=offset.bottom()),affix=null!=this.unpin&&scrollTop+this.unpin<=position.top?!1:null!=offsetBottom&&position.top+this.$element.height()>=scrollHeight-offsetBottom?"bottom":null!=offsetTop&&offsetTop>=scrollTop?"top":!1,this.affixed!==affix&&(this.affixed=affix,this.unpin="bottom"==affix?position.top-scrollTop:null,this.$element.removeClass(reset).addClass("affix"+(affix?"-"+affix:"")))}};var old=$.fn.affix;$.fn.affix=function(option){return this.each(function(){var $this=$(this),data=$this.data("affix"),options="object"==typeof option&&option;data||$this.data("affix",data=new Affix(this,options)),"string"==typeof option&&data[option]()})},$.fn.affix.Constructor=Affix,$.fn.affix.defaults={offset:0},$.fn.affix.noConflict=function(){return $.fn.affix=old,this},$(window).on("load",function(){$('[data-spy="affix"]').each(function(){var $spy=$(this),data=$spy.data();data.offset=data.offset||{},data.offsetBottom&&(data.offset.bottom=data.offsetBottom),data.offsetTop&&(data.offset.top=data.offsetTop),$spy.affix(data)})})}(window.jQuery);
--------------------------------------------------------------------------------
/sudoku.js:
--------------------------------------------------------------------------------
1 | /*
2 | Sudoku.js
3 | ---------
4 |
5 | A Sudoku puzzle generator and solver JavaScript library.
6 |
7 | Please see the README for more details.
8 | */
9 |
10 | (function(root){
11 | var sudoku = root.sudoku = {}; // Global reference to the sudoku library
12 |
13 | sudoku.DIGITS = "123456789"; // Allowed sudoku.DIGITS
14 | var ROWS = "ABCDEFGHI"; // Row lables
15 | var COLS = sudoku.DIGITS; // Column lables
16 | var SQUARES = null; // Square IDs
17 |
18 | var UNITS = null; // All units (row, column, or box)
19 | var SQUARE_UNITS_MAP = null; // Squares -> units map
20 | var SQUARE_PEERS_MAP = null; // Squares -> peers map
21 |
22 | var MIN_GIVENS = 17; // Minimum number of givens
23 | var NR_SQUARES = 81; // Number of squares
24 |
25 | // Define difficulties by how many squares are given to the player in a new
26 | // puzzle.
27 | var DIFFICULTY = {
28 | "easy": 62,
29 | "medium": 53,
30 | "hard": 44,
31 | "very-hard": 35,
32 | "insane": 26,
33 | "inhuman": 17,
34 | };
35 |
36 | // Blank character and board representation
37 | sudoku.BLANK_CHAR = '.';
38 | sudoku.BLANK_BOARD = "...................................................."+
39 | ".............................";
40 |
41 | // Init
42 | // -------------------------------------------------------------------------
43 | function initialize(){
44 | /* Initialize the Sudoku library (invoked after library load)
45 | */
46 | SQUARES = sudoku._cross(ROWS, COLS);
47 | UNITS = sudoku._get_all_units(ROWS, COLS);
48 | SQUARE_UNITS_MAP = sudoku._get_square_units_map(SQUARES, UNITS);
49 | SQUARE_PEERS_MAP = sudoku._get_square_peers_map(SQUARES,
50 | SQUARE_UNITS_MAP);
51 | }
52 |
53 | // Generate
54 | // -------------------------------------------------------------------------
55 | sudoku.generate = function(difficulty, unique){
56 | /* Generate a new Sudoku puzzle of a particular `difficulty`, e.g.,
57 |
58 | // Generate an "easy" sudoku puzzle
59 | sudoku.generate("easy");
60 |
61 |
62 | Difficulties are as follows, and represent the number of given squares:
63 |
64 | "easy": 61
65 | "medium": 52
66 | "hard": 43
67 | "very-hard": 34
68 | "insane": 25
69 | "inhuman": 17
70 |
71 |
72 | You may also enter a custom number of squares to be given, e.g.,
73 |
74 | // Generate a new Sudoku puzzle with 60 given squares
75 | sudoku.generate(60)
76 |
77 |
78 | `difficulty` must be a number between 17 and 81 inclusive. If it's
79 | outside of that range, `difficulty` will be set to the closest bound,
80 | e.g., 0 -> 17, and 100 -> 81.
81 |
82 |
83 | By default, the puzzles are unique, uless you set `unique` to false.
84 | (Note: Puzzle uniqueness is not yet implemented, so puzzles are *not*
85 | guaranteed to have unique solutions)
86 |
87 | TODO: Implement puzzle uniqueness
88 | */
89 |
90 | // If `difficulty` is a string or undefined, convert it to a number or
91 | // default it to "easy" if undefined.
92 | if(typeof difficulty === "string" || typeof difficulty === "undefined"){
93 | difficulty = DIFFICULTY[difficulty] || DIFFICULTY.easy;
94 | }
95 |
96 | // Force difficulty between 17 and 81 inclusive
97 | difficulty = sudoku._force_range(difficulty, NR_SQUARES + 1,
98 | MIN_GIVENS);
99 |
100 | // Default unique to true
101 | unique = unique || true;
102 |
103 | // Get a set of squares and all possible candidates for each square
104 | var blank_board = "";
105 | for(var i = 0; i < NR_SQUARES; ++i){
106 | blank_board += '.';
107 | }
108 | var candidates = sudoku._get_candidates_map(blank_board);
109 |
110 | // For each item in a shuffled list of squares
111 | var shuffled_squares = sudoku._shuffle(SQUARES);
112 | for(var si in shuffled_squares){
113 | var square = shuffled_squares[si];
114 |
115 | // If an assignment of a random chioce causes a contradictoin, give
116 | // up and try again
117 | var rand_candidate_idx =
118 | sudoku._rand_range(candidates[square].length);
119 | var rand_candidate = candidates[square][rand_candidate_idx];
120 | if(!sudoku._assign(candidates, square, rand_candidate)){
121 | break;
122 | }
123 |
124 | // Make a list of all single candidates
125 | var single_candidates = [];
126 | for(var si in SQUARES){
127 | var square = SQUARES[si];
128 |
129 | if(candidates[square].length == 1){
130 | single_candidates.push(candidates[square]);
131 | }
132 | }
133 |
134 | // If we have at least difficulty, and the unique candidate count is
135 | // at least 8, return the puzzle!
136 | if(single_candidates.length >= difficulty &&
137 | sudoku._strip_dups(single_candidates).length >= 8){
138 | var board = "";
139 | var givens_idxs = [];
140 | for(var i in SQUARES){
141 | var square = SQUARES[i];
142 | if(candidates[square].length == 1){
143 | board += candidates[square];
144 | givens_idxs.push(i);
145 | } else {
146 | board += sudoku.BLANK_CHAR;
147 | }
148 | }
149 |
150 | // If we have more than `difficulty` givens, remove some random
151 | // givens until we're down to exactly `difficulty`
152 | var nr_givens = givens_idxs.length;
153 | if(nr_givens > difficulty){
154 | givens_idxs = sudoku._shuffle(givens_idxs);
155 | for(var i = 0; i < nr_givens - difficulty; ++i){
156 | var target = parseInt(givens_idxs[i]);
157 | board = board.substr(0, target) + sudoku.BLANK_CHAR +
158 | board.substr(target + 1);
159 | }
160 | }
161 |
162 | // Double check board is solvable
163 | // TODO: Make a standalone board checker. Solve is expensive.
164 | if(sudoku.solve(board)){
165 | return board;
166 | }
167 | }
168 | }
169 |
170 | // Give up and try a new puzzle
171 | return sudoku.generate(difficulty);
172 | };
173 |
174 | // Solve
175 | // -------------------------------------------------------------------------
176 | sudoku.solve = function(board, reverse){
177 | /* Solve a sudoku puzzle given a sudoku `board`, i.e., an 81-character
178 | string of sudoku.DIGITS, 1-9, and spaces identified by '.', representing the
179 | squares. There must be a minimum of 17 givens. If the given board has no
180 | solutions, return false.
181 |
182 | Optionally set `reverse` to solve "backwards", i.e., rotate through the
183 | possibilities in reverse. Useful for checking if there is more than one
184 | solution.
185 | */
186 |
187 | // Assure a valid board
188 | var report = sudoku.validate_board(board);
189 | if(report !== true){
190 | throw report;
191 | }
192 |
193 | // Check number of givens is at least MIN_GIVENS
194 | var nr_givens = 0;
195 | for(var i in board){
196 | if(board[i] !== sudoku.BLANK_CHAR && sudoku._in(board[i], sudoku.DIGITS)){
197 | ++nr_givens;
198 | }
199 | }
200 | if(nr_givens < MIN_GIVENS){
201 | throw "Too few givens. Minimum givens is " + MIN_GIVENS;
202 | }
203 |
204 | // Default reverse to false
205 | reverse = reverse || false;
206 |
207 | var candidates = sudoku._get_candidates_map(board);
208 | var result = sudoku._search(candidates, reverse);
209 |
210 | if(result){
211 | var solution = "";
212 | for(var square in result){
213 | solution += result[square];
214 | }
215 | return solution;
216 | }
217 | return false;
218 | };
219 |
220 | sudoku.get_candidates = function(board){
221 | /* Return all possible candidatees for each square as a grid of
222 | candidates, returnning `false` if a contradiction is encountered.
223 |
224 | Really just a wrapper for sudoku._get_candidates_map for programmer
225 | consumption.
226 | */
227 |
228 | // Assure a valid board
229 | var report = sudoku.validate_board(board);
230 | if(report !== true){
231 | throw report;
232 | }
233 |
234 | // Get a candidates map
235 | var candidates_map = sudoku._get_candidates_map(board);
236 |
237 | // If there's an error, return false
238 | if(!candidates_map){
239 | return false;
240 | }
241 |
242 | // Transform candidates map into grid
243 | var rows = [];
244 | var cur_row = [];
245 | var i = 0;
246 | for(var square in candidates_map){
247 | var candidates = candidates_map[square];
248 | cur_row.push(candidates);
249 | if(i % 9 == 8){
250 | rows.push(cur_row);
251 | cur_row = [];
252 | }
253 | ++i;
254 | }
255 | return rows;
256 | }
257 |
258 | sudoku._get_candidates_map = function(board){
259 | /* Get all possible candidates for each square as a map in the form
260 | {square: sudoku.DIGITS} using recursive constraint propagation. Return `false`
261 | if a contradiction is encountered
262 | */
263 |
264 | // Assure a valid board
265 | var report = sudoku.validate_board(board);
266 | if(report !== true){
267 | throw report;
268 | }
269 |
270 | var candidate_map = {};
271 | var squares_values_map = sudoku._get_square_vals_map(board);
272 |
273 | // Start by assigning every digit as a candidate to every square
274 | for(var si in SQUARES){
275 | candidate_map[SQUARES[si]] = sudoku.DIGITS;
276 | }
277 |
278 | // For each non-blank square, assign its value in the candidate map and
279 | // propigate.
280 | for(var square in squares_values_map){
281 | var val = squares_values_map[square];
282 |
283 | if(sudoku._in(val, sudoku.DIGITS)){
284 | var new_candidates = sudoku._assign(candidate_map, square, val);
285 |
286 | // Fail if we can't assign val to square
287 | if(!new_candidates){
288 | return false;
289 | }
290 | }
291 | }
292 |
293 | return candidate_map;
294 | };
295 |
296 | sudoku._search = function(candidates, reverse){
297 | /* Given a map of squares -> candiates, using depth-first search,
298 | recursively try all possible values until a solution is found, or false
299 | if no solution exists.
300 | */
301 |
302 | // Return if error in previous iteration
303 | if(!candidates){
304 | return false;
305 | }
306 |
307 | // Default reverse to false
308 | reverse = reverse || false;
309 |
310 | // If only one candidate for every square, we've a solved puzzle!
311 | // Return the candidates map.
312 | var max_nr_candidates = 0;
313 | var max_candidates_square = null;
314 | for(var si in SQUARES){
315 | var square = SQUARES[si];
316 |
317 | var nr_candidates = candidates[square].length;
318 |
319 | if(nr_candidates > max_nr_candidates){
320 | max_nr_candidates = nr_candidates;
321 | max_candidates_square = square;
322 | }
323 | }
324 | if(max_nr_candidates === 1){
325 | return candidates;
326 | }
327 |
328 | // Choose the blank square with the fewest possibilities > 1
329 | var min_nr_candidates = 10;
330 | var min_candidates_square = null;
331 | for(si in SQUARES){
332 | var square = SQUARES[si];
333 |
334 | var nr_candidates = candidates[square].length;
335 |
336 | if(nr_candidates < min_nr_candidates && nr_candidates > 1){
337 | min_nr_candidates = nr_candidates;
338 | min_candidates_square = square;
339 | }
340 | }
341 |
342 | // Recursively search through each of the candidates of the square
343 | // starting with the one with fewest candidates.
344 |
345 | // Rotate through the candidates forwards
346 | var min_candidates = candidates[min_candidates_square];
347 | if(!reverse){
348 | for(var vi in min_candidates){
349 | var val = min_candidates[vi];
350 |
351 | // TODO: Implement a non-rediculous deep copy function
352 | var candidates_copy = JSON.parse(JSON.stringify(candidates));
353 | var candidates_next = sudoku._search(
354 | sudoku._assign(candidates_copy, min_candidates_square, val)
355 | );
356 |
357 | if(candidates_next){
358 | return candidates_next;
359 | }
360 | }
361 |
362 | // Rotate through the candidates backwards
363 | } else {
364 | for(var vi = min_candidates.length - 1; vi >= 0; --vi){
365 | var val = min_candidates[vi];
366 |
367 | // TODO: Implement a non-rediculous deep copy function
368 | var candidates_copy = JSON.parse(JSON.stringify(candidates));
369 | var candidates_next = sudoku._search(
370 | sudoku._assign(candidates_copy, min_candidates_square, val),
371 | reverse
372 | );
373 |
374 | if(candidates_next){
375 | return candidates_next;
376 | }
377 | }
378 | }
379 |
380 | // If we get through all combinations of the square with the fewest
381 | // candidates without finding an answer, there isn't one. Return false.
382 | return false;
383 | };
384 |
385 | sudoku._assign = function(candidates, square, val){
386 | /* Eliminate all values, *except* for `val`, from `candidates` at
387 | `square` (candidates[square]), and propagate. Return the candidates map
388 | when finished. If a contradiciton is found, return false.
389 |
390 | WARNING: This will modify the contents of `candidates` directly.
391 | */
392 |
393 | // Grab a list of canidates without 'val'
394 | var other_vals = candidates[square].replace(val, "");
395 |
396 | // Loop through all other values and eliminate them from the candidates
397 | // at the current square, and propigate. If at any point we get a
398 | // contradiction, return false.
399 | for(var ovi in other_vals){
400 | var other_val = other_vals[ovi];
401 |
402 | var candidates_next =
403 | sudoku._eliminate(candidates, square, other_val);
404 |
405 | if(!candidates_next){
406 | //console.log("Contradiction found by _eliminate.");
407 | return false;
408 | }
409 | }
410 |
411 | return candidates;
412 | };
413 |
414 | sudoku._eliminate = function(candidates, square, val){
415 | /* Eliminate `val` from `candidates` at `square`, (candidates[square]),
416 | and propagate when values or places <= 2. Return updated candidates,
417 | unless a contradiction is detected, in which case, return false.
418 |
419 | WARNING: This will modify the contents of `candidates` directly.
420 | */
421 |
422 | // If `val` has already been eliminated from candidates[square], return
423 | // with candidates.
424 | if(!sudoku._in(val, candidates[square])){
425 | return candidates;
426 | }
427 |
428 | // Remove `val` from candidates[square]
429 | candidates[square] = candidates[square].replace(val, '');
430 |
431 | // If the square has only candidate left, eliminate that value from its
432 | // peers
433 | var nr_candidates = candidates[square].length;
434 | if(nr_candidates === 1){
435 | var target_val = candidates[square];
436 |
437 | for(var pi in SQUARE_PEERS_MAP[square]){
438 | var peer = SQUARE_PEERS_MAP[square][pi];
439 |
440 | var candidates_new =
441 | sudoku._eliminate(candidates, peer, target_val);
442 |
443 | if(!candidates_new){
444 | return false;
445 | }
446 | }
447 |
448 | // Otherwise, if the square has no candidates, we have a contradiction.
449 | // Return false.
450 | } if(nr_candidates === 0){
451 | return false;
452 | }
453 |
454 | // If a unit is reduced to only one place for a value, then assign it
455 | for(var ui in SQUARE_UNITS_MAP[square]){
456 | var unit = SQUARE_UNITS_MAP[square][ui];
457 |
458 | var val_places = [];
459 | for(var si in unit){
460 | var unit_square = unit[si];
461 | if(sudoku._in(val, candidates[unit_square])){
462 | val_places.push(unit_square);
463 | }
464 | }
465 |
466 | // If there's no place for this value, we have a contradition!
467 | // return false
468 | if(val_places.length === 0){
469 | return false;
470 |
471 | // Otherwise the value can only be in one place. Assign it there.
472 | } else if(val_places.length === 1){
473 | var candidates_new =
474 | sudoku._assign(candidates, val_places[0], val);
475 |
476 | if(!candidates_new){
477 | return false;
478 | }
479 | }
480 | }
481 |
482 | return candidates;
483 | };
484 |
485 |
486 | // Square relationships
487 | // -------------------------------------------------------------------------
488 | // Squares, and their relationships with values, units, and peers.
489 |
490 | sudoku._get_square_vals_map = function(board){
491 | /* Return a map of squares -> values
492 | */
493 | var squares_vals_map = {};
494 |
495 | // Make sure `board` is a string of length 81
496 | if(board.length != SQUARES.length){
497 | throw "Board/squares length mismatch.";
498 |
499 | } else {
500 | for(var i in SQUARES){
501 | squares_vals_map[SQUARES[i]] = board[i];
502 | }
503 | }
504 |
505 | return squares_vals_map;
506 | };
507 |
508 | sudoku._get_square_units_map = function(squares, units){
509 | /* Return a map of `squares` and their associated units (row, col, box)
510 | */
511 | var square_unit_map = {};
512 |
513 | // For every square...
514 | for(var si in squares){
515 | var cur_square = squares[si];
516 |
517 | // Maintain a list of the current square's units
518 | var cur_square_units = [];
519 |
520 | // Look through the units, and see if the current square is in it,
521 | // and if so, add it to the list of of the square's units.
522 | for(var ui in units){
523 | var cur_unit = units[ui];
524 |
525 | if(cur_unit.indexOf(cur_square) !== -1){
526 | cur_square_units.push(cur_unit);
527 | }
528 | }
529 |
530 | // Save the current square and its units to the map
531 | square_unit_map[cur_square] = cur_square_units;
532 | }
533 |
534 | return square_unit_map;
535 | };
536 |
537 | sudoku._get_square_peers_map = function(squares, units_map){
538 | /* Return a map of `squares` and their associated peers, i.e., a set of
539 | other squares in the square's unit.
540 | */
541 | var square_peers_map = {};
542 |
543 | // For every square...
544 | for(var si in squares){
545 | var cur_square = squares[si];
546 | var cur_square_units = units_map[cur_square];
547 |
548 | // Maintain list of the current square's peers
549 | var cur_square_peers = [];
550 |
551 | // Look through the current square's units map...
552 | for(var sui in cur_square_units){
553 | var cur_unit = cur_square_units[sui];
554 |
555 | for(var ui in cur_unit){
556 | var cur_unit_square = cur_unit[ui];
557 |
558 | if(cur_square_peers.indexOf(cur_unit_square) === -1 &&
559 | cur_unit_square !== cur_square){
560 | cur_square_peers.push(cur_unit_square);
561 | }
562 | }
563 | }
564 |
565 | // Save the current square an its associated peers to the map
566 | square_peers_map[cur_square] = cur_square_peers;
567 | }
568 |
569 | return square_peers_map;
570 | };
571 |
572 | sudoku._get_all_units = function(rows, cols){
573 | /* Return a list of all units (rows, cols, boxes)
574 | */
575 | var units = [];
576 |
577 | // Rows
578 | for(var ri in rows){
579 | units.push(sudoku._cross(rows[ri], cols));
580 | }
581 |
582 | // Columns
583 | for(var ci in cols){
584 | units.push(sudoku._cross(rows, cols[ci]));
585 | }
586 |
587 | // Boxes
588 | var row_squares = ["ABC", "DEF", "GHI"];
589 | var col_squares = ["123", "456", "789"];
590 | for(var rsi in row_squares){
591 | for(var csi in col_squares){
592 | units.push(sudoku._cross(row_squares[rsi], col_squares[csi]));
593 | }
594 | }
595 |
596 | return units;
597 | };
598 |
599 |
600 | // Conversions
601 | // -------------------------------------------------------------------------
602 | sudoku.board_string_to_grid = function(board_string){
603 | /* Convert a board string to a two-dimensional array
604 | */
605 | var rows = [];
606 | var cur_row = [];
607 | for(var i in board_string){
608 | cur_row.push(board_string[i]);
609 | if(i % 9 == 8){
610 | rows.push(cur_row);
611 | cur_row = [];
612 | }
613 | }
614 | return rows;
615 | };
616 |
617 | sudoku.board_grid_to_string = function(board_grid){
618 | /* Convert a board grid to a string
619 | */
620 | var board_string = "";
621 | for(var r = 0; r < 9; ++r){
622 | for(var c = 0; c < 9; ++c){
623 | board_string += board_grid[r][c];
624 | }
625 | }
626 | return board_string;
627 | };
628 |
629 |
630 | // Utility
631 | // -------------------------------------------------------------------------
632 |
633 | sudoku.print_board = function(board){
634 | /* Print a sudoku `board` to the console.
635 | */
636 |
637 | // Assure a valid board
638 | var report = sudoku.validate_board(board);
639 | if(report !== true){
640 | throw report;
641 | }
642 |
643 | var V_PADDING = " "; // Insert after each square
644 | var H_PADDING = '\n'; // Insert after each row
645 |
646 | var V_BOX_PADDING = " "; // Box vertical padding
647 | var H_BOX_PADDING = '\n'; // Box horizontal padding
648 |
649 | var display_string = "";
650 |
651 | for(var i in board){
652 | var square = board[i];
653 |
654 | // Add the square and some padding
655 | display_string += square + V_PADDING;
656 |
657 | // Vertical edge of a box, insert v. box padding
658 | if(i % 3 === 2){
659 | display_string += V_BOX_PADDING;
660 | }
661 |
662 | // End of a line, insert horiz. padding
663 | if(i % 9 === 8){
664 | display_string += H_PADDING;
665 | }
666 |
667 | // Horizontal edge of a box, insert h. box padding
668 | if(i % 27 === 26){
669 | display_string += H_BOX_PADDING;
670 | }
671 | }
672 |
673 | console.log(display_string);
674 | };
675 |
676 | sudoku.validate_board = function(board){
677 | /* Return if the given `board` is valid or not. If it's valid, return
678 | true. If it's not, return a string of the reason why it's not.
679 | */
680 |
681 | // Check for empty board
682 | if(!board){
683 | return "Empty board";
684 | }
685 |
686 | // Invalid board length
687 | if(board.length !== NR_SQUARES){
688 | return "Invalid board size. Board must be exactly " + NR_SQUARES +
689 | " squares.";
690 | }
691 |
692 | // Check for invalid characters
693 | for(var i in board){
694 | if(!sudoku._in(board[i], sudoku.DIGITS) && board[i] !== sudoku.BLANK_CHAR){
695 | return "Invalid board character encountered at index " + i +
696 | ": " + board[i];
697 | }
698 | }
699 |
700 | // Otherwise, we're good. Return true.
701 | return true;
702 | };
703 |
704 | sudoku._cross = function(a, b){
705 | /* Cross product of all elements in `a` and `b`, e.g.,
706 | sudoku._cross("abc", "123") ->
707 | ["a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3"]
708 | */
709 | var result = [];
710 | for(var ai in a){
711 | for(var bi in b){
712 | result.push(a[ai] + b[bi]);
713 | }
714 | }
715 | return result;
716 | };
717 |
718 | sudoku._in = function(v, seq){
719 | /* Return if a value `v` is in sequence `seq`.
720 | */
721 | return seq.indexOf(v) !== -1;
722 | };
723 |
724 | sudoku._first_true = function(seq){
725 | /* Return the first element in `seq` that is true. If no element is
726 | true, return false.
727 | */
728 | for(var i in seq){
729 | if(seq[i]){
730 | return seq[i];
731 | }
732 | }
733 | return false;
734 | };
735 |
736 | sudoku._shuffle = function(seq){
737 | /* Return a shuffled version of `seq`
738 | */
739 |
740 | // Create an array of the same size as `seq` filled with false
741 | var shuffled = [];
742 | for(var i = 0; i < seq.length; ++i){
743 | shuffled.push(false);
744 | }
745 |
746 | for(var i in seq){
747 | var ti = sudoku._rand_range(seq.length);
748 |
749 | while(shuffled[ti]){
750 | ti = (ti + 1) > (seq.length - 1) ? 0 : (ti + 1);
751 | }
752 |
753 | shuffled[ti] = seq[i];
754 | }
755 |
756 | return shuffled;
757 | };
758 |
759 | sudoku._rand_range = function(max, min){
760 | /* Get a random integer in the range of `min` to `max` (non inclusive).
761 | If `min` not defined, default to 0. If `max` not defined, throw an
762 | error.
763 | */
764 | min = min || 0;
765 | if(max){
766 | return Math.floor(Math.random() * (max - min)) + min;
767 | } else {
768 | throw "Range undefined";
769 | }
770 | };
771 |
772 | sudoku._strip_dups = function(seq){
773 | /* Strip duplicate values from `seq`
774 | */
775 | var seq_set = [];
776 | var dup_map = {};
777 | for(var i in seq){
778 | var e = seq[i];
779 | if(!dup_map[e]){
780 | seq_set.push(e);
781 | dup_map[e] = true;
782 | }
783 | }
784 | return seq_set;
785 | };
786 |
787 | sudoku._force_range = function(nr, max, min){
788 | /* Force `nr` to be within the range from `min` to, but not including,
789 | `max`. `min` is optional, and will default to 0. If `nr` is undefined,
790 | treat it as zero.
791 | */
792 | min = min || 0
793 | nr = nr || 0
794 | if(nr < min){
795 | return min;
796 | }
797 | if(nr > max){
798 | return max;
799 | }
800 | return nr
801 | }
802 |
803 | // Initialize library after load
804 | initialize();
805 |
806 | // Pass whatever the root object is, lsike 'window' in browsers
807 | })(this);
--------------------------------------------------------------------------------
/test/qunit/qunit-1.11.0.js:
--------------------------------------------------------------------------------
1 | /**
2 | * QUnit v1.11.0 - A JavaScript Unit Testing Framework
3 | *
4 | * http://qunitjs.com
5 | *
6 | * Copyright 2012 jQuery Foundation and other contributors
7 | * Released under the MIT license.
8 | * http://jquery.org/license
9 | */
10 |
11 | (function( window ) {
12 |
13 | var QUnit,
14 | assert,
15 | config,
16 | onErrorFnPrev,
17 | testId = 0,
18 | fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""),
19 | toString = Object.prototype.toString,
20 | hasOwn = Object.prototype.hasOwnProperty,
21 | // Keep a local reference to Date (GH-283)
22 | Date = window.Date,
23 | defined = {
24 | setTimeout: typeof window.setTimeout !== "undefined",
25 | sessionStorage: (function() {
26 | var x = "qunit-test-string";
27 | try {
28 | sessionStorage.setItem( x, x );
29 | sessionStorage.removeItem( x );
30 | return true;
31 | } catch( e ) {
32 | return false;
33 | }
34 | }())
35 | },
36 | /**
37 | * Provides a normalized error string, correcting an issue
38 | * with IE 7 (and prior) where Error.prototype.toString is
39 | * not properly implemented
40 | *
41 | * Based on http://es5.github.com/#x15.11.4.4
42 | *
43 | * @param {String|Error} error
44 | * @return {String} error message
45 | */
46 | errorString = function( error ) {
47 | var name, message,
48 | errorString = error.toString();
49 | if ( errorString.substring( 0, 7 ) === "[object" ) {
50 | name = error.name ? error.name.toString() : "Error";
51 | message = error.message ? error.message.toString() : "";
52 | if ( name && message ) {
53 | return name + ": " + message;
54 | } else if ( name ) {
55 | return name;
56 | } else if ( message ) {
57 | return message;
58 | } else {
59 | return "Error";
60 | }
61 | } else {
62 | return errorString;
63 | }
64 | },
65 | /**
66 | * Makes a clone of an object using only Array or Object as base,
67 | * and copies over the own enumerable properties.
68 | *
69 | * @param {Object} obj
70 | * @return {Object} New object with only the own properties (recursively).
71 | */
72 | objectValues = function( obj ) {
73 | // Grunt 0.3.x uses an older version of jshint that still has jshint/jshint#392.
74 | /*jshint newcap: false */
75 | var key, val,
76 | vals = QUnit.is( "array", obj ) ? [] : {};
77 | for ( key in obj ) {
78 | if ( hasOwn.call( obj, key ) ) {
79 | val = obj[key];
80 | vals[key] = val === Object(val) ? objectValues(val) : val;
81 | }
82 | }
83 | return vals;
84 | };
85 |
86 | function Test( settings ) {
87 | extend( this, settings );
88 | this.assertions = [];
89 | this.testNumber = ++Test.count;
90 | }
91 |
92 | Test.count = 0;
93 |
94 | Test.prototype = {
95 | init: function() {
96 | var a, b, li,
97 | tests = id( "qunit-tests" );
98 |
99 | if ( tests ) {
100 | b = document.createElement( "strong" );
101 | b.innerHTML = this.nameHtml;
102 |
103 | // `a` initialized at top of scope
104 | a = document.createElement( "a" );
105 | a.innerHTML = "Rerun";
106 | a.href = QUnit.url({ testNumber: this.testNumber });
107 |
108 | li = document.createElement( "li" );
109 | li.appendChild( b );
110 | li.appendChild( a );
111 | li.className = "running";
112 | li.id = this.id = "qunit-test-output" + testId++;
113 |
114 | tests.appendChild( li );
115 | }
116 | },
117 | setup: function() {
118 | if ( this.module !== config.previousModule ) {
119 | if ( config.previousModule ) {
120 | runLoggingCallbacks( "moduleDone", QUnit, {
121 | name: config.previousModule,
122 | failed: config.moduleStats.bad,
123 | passed: config.moduleStats.all - config.moduleStats.bad,
124 | total: config.moduleStats.all
125 | });
126 | }
127 | config.previousModule = this.module;
128 | config.moduleStats = { all: 0, bad: 0 };
129 | runLoggingCallbacks( "moduleStart", QUnit, {
130 | name: this.module
131 | });
132 | } else if ( config.autorun ) {
133 | runLoggingCallbacks( "moduleStart", QUnit, {
134 | name: this.module
135 | });
136 | }
137 |
138 | config.current = this;
139 |
140 | this.testEnvironment = extend({
141 | setup: function() {},
142 | teardown: function() {}
143 | }, this.moduleTestEnvironment );
144 |
145 | this.started = +new Date();
146 | runLoggingCallbacks( "testStart", QUnit, {
147 | name: this.testName,
148 | module: this.module
149 | });
150 |
151 | // allow utility functions to access the current test environment
152 | // TODO why??
153 | QUnit.current_testEnvironment = this.testEnvironment;
154 |
155 | if ( !config.pollution ) {
156 | saveGlobal();
157 | }
158 | if ( config.notrycatch ) {
159 | this.testEnvironment.setup.call( this.testEnvironment );
160 | return;
161 | }
162 | try {
163 | this.testEnvironment.setup.call( this.testEnvironment );
164 | } catch( e ) {
165 | QUnit.pushFailure( "Setup failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) );
166 | }
167 | },
168 | run: function() {
169 | config.current = this;
170 |
171 | var running = id( "qunit-testresult" );
172 |
173 | if ( running ) {
174 | running.innerHTML = "Running:
" + this.nameHtml;
175 | }
176 |
177 | if ( this.async ) {
178 | QUnit.stop();
179 | }
180 |
181 | this.callbackStarted = +new Date();
182 |
183 | if ( config.notrycatch ) {
184 | this.callback.call( this.testEnvironment, QUnit.assert );
185 | this.callbackRuntime = +new Date() - this.callbackStarted;
186 | return;
187 | }
188 |
189 | try {
190 | this.callback.call( this.testEnvironment, QUnit.assert );
191 | this.callbackRuntime = +new Date() - this.callbackStarted;
192 | } catch( e ) {
193 | this.callbackRuntime = +new Date() - this.callbackStarted;
194 |
195 | QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) );
196 | // else next test will carry the responsibility
197 | saveGlobal();
198 |
199 | // Restart the tests if they're blocking
200 | if ( config.blocking ) {
201 | QUnit.start();
202 | }
203 | }
204 | },
205 | teardown: function() {
206 | config.current = this;
207 | if ( config.notrycatch ) {
208 | if ( typeof this.callbackRuntime === "undefined" ) {
209 | this.callbackRuntime = +new Date() - this.callbackStarted;
210 | }
211 | this.testEnvironment.teardown.call( this.testEnvironment );
212 | return;
213 | } else {
214 | try {
215 | this.testEnvironment.teardown.call( this.testEnvironment );
216 | } catch( e ) {
217 | QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) );
218 | }
219 | }
220 | checkPollution();
221 | },
222 | finish: function() {
223 | config.current = this;
224 | if ( config.requireExpects && this.expected === null ) {
225 | QUnit.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack );
226 | } else if ( this.expected !== null && this.expected !== this.assertions.length ) {
227 | QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack );
228 | } else if ( this.expected === null && !this.assertions.length ) {
229 | QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack );
230 | }
231 |
232 | var i, assertion, a, b, time, li, ol,
233 | test = this,
234 | good = 0,
235 | bad = 0,
236 | tests = id( "qunit-tests" );
237 |
238 | this.runtime = +new Date() - this.started;
239 | config.stats.all += this.assertions.length;
240 | config.moduleStats.all += this.assertions.length;
241 |
242 | if ( tests ) {
243 | ol = document.createElement( "ol" );
244 | ol.className = "qunit-assert-list";
245 |
246 | for ( i = 0; i < this.assertions.length; i++ ) {
247 | assertion = this.assertions[i];
248 |
249 | li = document.createElement( "li" );
250 | li.className = assertion.result ? "pass" : "fail";
251 | li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" );
252 | ol.appendChild( li );
253 |
254 | if ( assertion.result ) {
255 | good++;
256 | } else {
257 | bad++;
258 | config.stats.bad++;
259 | config.moduleStats.bad++;
260 | }
261 | }
262 |
263 | // store result when possible
264 | if ( QUnit.config.reorder && defined.sessionStorage ) {
265 | if ( bad ) {
266 | sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad );
267 | } else {
268 | sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName );
269 | }
270 | }
271 |
272 | if ( bad === 0 ) {
273 | addClass( ol, "qunit-collapsed" );
274 | }
275 |
276 | // `b` initialized at top of scope
277 | b = document.createElement( "strong" );
278 | b.innerHTML = this.nameHtml + " (" + bad + ", " + good + ", " + this.assertions.length + ")";
279 |
280 | addEvent(b, "click", function() {
281 | var next = b.parentNode.lastChild,
282 | collapsed = hasClass( next, "qunit-collapsed" );
283 | ( collapsed ? removeClass : addClass )( next, "qunit-collapsed" );
284 | });
285 |
286 | addEvent(b, "dblclick", function( e ) {
287 | var target = e && e.target ? e.target : window.event.srcElement;
288 | if ( target.nodeName.toLowerCase() === "span" || target.nodeName.toLowerCase() === "b" ) {
289 | target = target.parentNode;
290 | }
291 | if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
292 | window.location = QUnit.url({ testNumber: test.testNumber });
293 | }
294 | });
295 |
296 | // `time` initialized at top of scope
297 | time = document.createElement( "span" );
298 | time.className = "runtime";
299 | time.innerHTML = this.runtime + " ms";
300 |
301 | // `li` initialized at top of scope
302 | li = id( this.id );
303 | li.className = bad ? "fail" : "pass";
304 | li.removeChild( li.firstChild );
305 | a = li.firstChild;
306 | li.appendChild( b );
307 | li.appendChild( a );
308 | li.appendChild( time );
309 | li.appendChild( ol );
310 |
311 | } else {
312 | for ( i = 0; i < this.assertions.length; i++ ) {
313 | if ( !this.assertions[i].result ) {
314 | bad++;
315 | config.stats.bad++;
316 | config.moduleStats.bad++;
317 | }
318 | }
319 | }
320 |
321 | runLoggingCallbacks( "testDone", QUnit, {
322 | name: this.testName,
323 | module: this.module,
324 | failed: bad,
325 | passed: this.assertions.length - bad,
326 | total: this.assertions.length,
327 | duration: this.runtime
328 | });
329 |
330 | QUnit.reset();
331 |
332 | config.current = undefined;
333 | },
334 |
335 | queue: function() {
336 | var bad,
337 | test = this;
338 |
339 | synchronize(function() {
340 | test.init();
341 | });
342 | function run() {
343 | // each of these can by async
344 | synchronize(function() {
345 | test.setup();
346 | });
347 | synchronize(function() {
348 | test.run();
349 | });
350 | synchronize(function() {
351 | test.teardown();
352 | });
353 | synchronize(function() {
354 | test.finish();
355 | });
356 | }
357 |
358 | // `bad` initialized at top of scope
359 | // defer when previous test run passed, if storage is available
360 | bad = QUnit.config.reorder && defined.sessionStorage &&
361 | +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName );
362 |
363 | if ( bad ) {
364 | run();
365 | } else {
366 | synchronize( run, true );
367 | }
368 | }
369 | };
370 |
371 | // Root QUnit object.
372 | // `QUnit` initialized at top of scope
373 | QUnit = {
374 |
375 | // call on start of module test to prepend name to all tests
376 | module: function( name, testEnvironment ) {
377 | config.currentModule = name;
378 | config.currentModuleTestEnvironment = testEnvironment;
379 | config.modules[name] = true;
380 | },
381 |
382 | asyncTest: function( testName, expected, callback ) {
383 | if ( arguments.length === 2 ) {
384 | callback = expected;
385 | expected = null;
386 | }
387 |
388 | QUnit.test( testName, expected, callback, true );
389 | },
390 |
391 | test: function( testName, expected, callback, async ) {
392 | var test,
393 | nameHtml = "" + escapeText( testName ) + "";
394 |
395 | if ( arguments.length === 2 ) {
396 | callback = expected;
397 | expected = null;
398 | }
399 |
400 | if ( config.currentModule ) {
401 | nameHtml = "" + escapeText( config.currentModule ) + ": " + nameHtml;
402 | }
403 |
404 | test = new Test({
405 | nameHtml: nameHtml,
406 | testName: testName,
407 | expected: expected,
408 | async: async,
409 | callback: callback,
410 | module: config.currentModule,
411 | moduleTestEnvironment: config.currentModuleTestEnvironment,
412 | stack: sourceFromStacktrace( 2 )
413 | });
414 |
415 | if ( !validTest( test ) ) {
416 | return;
417 | }
418 |
419 | test.queue();
420 | },
421 |
422 | // Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
423 | expect: function( asserts ) {
424 | if (arguments.length === 1) {
425 | config.current.expected = asserts;
426 | } else {
427 | return config.current.expected;
428 | }
429 | },
430 |
431 | start: function( count ) {
432 | // QUnit hasn't been initialized yet.
433 | // Note: RequireJS (et al) may delay onLoad
434 | if ( config.semaphore === undefined ) {
435 | QUnit.begin(function() {
436 | // This is triggered at the top of QUnit.load, push start() to the event loop, to allow QUnit.load to finish first
437 | setTimeout(function() {
438 | QUnit.start( count );
439 | });
440 | });
441 | return;
442 | }
443 |
444 | config.semaphore -= count || 1;
445 | // don't start until equal number of stop-calls
446 | if ( config.semaphore > 0 ) {
447 | return;
448 | }
449 | // ignore if start is called more often then stop
450 | if ( config.semaphore < 0 ) {
451 | config.semaphore = 0;
452 | QUnit.pushFailure( "Called start() while already started (QUnit.config.semaphore was 0 already)", null, sourceFromStacktrace(2) );
453 | return;
454 | }
455 | // A slight delay, to avoid any current callbacks
456 | if ( defined.setTimeout ) {
457 | window.setTimeout(function() {
458 | if ( config.semaphore > 0 ) {
459 | return;
460 | }
461 | if ( config.timeout ) {
462 | clearTimeout( config.timeout );
463 | }
464 |
465 | config.blocking = false;
466 | process( true );
467 | }, 13);
468 | } else {
469 | config.blocking = false;
470 | process( true );
471 | }
472 | },
473 |
474 | stop: function( count ) {
475 | config.semaphore += count || 1;
476 | config.blocking = true;
477 |
478 | if ( config.testTimeout && defined.setTimeout ) {
479 | clearTimeout( config.timeout );
480 | config.timeout = window.setTimeout(function() {
481 | QUnit.ok( false, "Test timed out" );
482 | config.semaphore = 1;
483 | QUnit.start();
484 | }, config.testTimeout );
485 | }
486 | }
487 | };
488 |
489 | // `assert` initialized at top of scope
490 | // Asssert helpers
491 | // All of these must either call QUnit.push() or manually do:
492 | // - runLoggingCallbacks( "log", .. );
493 | // - config.current.assertions.push({ .. });
494 | // We attach it to the QUnit object *after* we expose the public API,
495 | // otherwise `assert` will become a global variable in browsers (#341).
496 | assert = {
497 | /**
498 | * Asserts rough true-ish result.
499 | * @name ok
500 | * @function
501 | * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
502 | */
503 | ok: function( result, msg ) {
504 | if ( !config.current ) {
505 | throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) );
506 | }
507 | result = !!result;
508 |
509 | var source,
510 | details = {
511 | module: config.current.module,
512 | name: config.current.testName,
513 | result: result,
514 | message: msg
515 | };
516 |
517 | msg = escapeText( msg || (result ? "okay" : "failed" ) );
518 | msg = "" + msg + "";
519 |
520 | if ( !result ) {
521 | source = sourceFromStacktrace( 2 );
522 | if ( source ) {
523 | details.source = source;
524 | msg += "| Source: | " + escapeText( source ) + " |
|---|
";
525 | }
526 | }
527 | runLoggingCallbacks( "log", QUnit, details );
528 | config.current.assertions.push({
529 | result: result,
530 | message: msg
531 | });
532 | },
533 |
534 | /**
535 | * Assert that the first two arguments are equal, with an optional message.
536 | * Prints out both actual and expected values.
537 | * @name equal
538 | * @function
539 | * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" );
540 | */
541 | equal: function( actual, expected, message ) {
542 | /*jshint eqeqeq:false */
543 | QUnit.push( expected == actual, actual, expected, message );
544 | },
545 |
546 | /**
547 | * @name notEqual
548 | * @function
549 | */
550 | notEqual: function( actual, expected, message ) {
551 | /*jshint eqeqeq:false */
552 | QUnit.push( expected != actual, actual, expected, message );
553 | },
554 |
555 | /**
556 | * @name propEqual
557 | * @function
558 | */
559 | propEqual: function( actual, expected, message ) {
560 | actual = objectValues(actual);
561 | expected = objectValues(expected);
562 | QUnit.push( QUnit.equiv(actual, expected), actual, expected, message );
563 | },
564 |
565 | /**
566 | * @name notPropEqual
567 | * @function
568 | */
569 | notPropEqual: function( actual, expected, message ) {
570 | actual = objectValues(actual);
571 | expected = objectValues(expected);
572 | QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message );
573 | },
574 |
575 | /**
576 | * @name deepEqual
577 | * @function
578 | */
579 | deepEqual: function( actual, expected, message ) {
580 | QUnit.push( QUnit.equiv(actual, expected), actual, expected, message );
581 | },
582 |
583 | /**
584 | * @name notDeepEqual
585 | * @function
586 | */
587 | notDeepEqual: function( actual, expected, message ) {
588 | QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message );
589 | },
590 |
591 | /**
592 | * @name strictEqual
593 | * @function
594 | */
595 | strictEqual: function( actual, expected, message ) {
596 | QUnit.push( expected === actual, actual, expected, message );
597 | },
598 |
599 | /**
600 | * @name notStrictEqual
601 | * @function
602 | */
603 | notStrictEqual: function( actual, expected, message ) {
604 | QUnit.push( expected !== actual, actual, expected, message );
605 | },
606 |
607 | "throws": function( block, expected, message ) {
608 | var actual,
609 | expectedOutput = expected,
610 | ok = false;
611 |
612 | // 'expected' is optional
613 | if ( typeof expected === "string" ) {
614 | message = expected;
615 | expected = null;
616 | }
617 |
618 | config.current.ignoreGlobalErrors = true;
619 | try {
620 | block.call( config.current.testEnvironment );
621 | } catch (e) {
622 | actual = e;
623 | }
624 | config.current.ignoreGlobalErrors = false;
625 |
626 | if ( actual ) {
627 | // we don't want to validate thrown error
628 | if ( !expected ) {
629 | ok = true;
630 | expectedOutput = null;
631 | // expected is a regexp
632 | } else if ( QUnit.objectType( expected ) === "regexp" ) {
633 | ok = expected.test( errorString( actual ) );
634 | // expected is a constructor
635 | } else if ( actual instanceof expected ) {
636 | ok = true;
637 | // expected is a validation function which returns true is validation passed
638 | } else if ( expected.call( {}, actual ) === true ) {
639 | expectedOutput = null;
640 | ok = true;
641 | }
642 |
643 | QUnit.push( ok, actual, expectedOutput, message );
644 | } else {
645 | QUnit.pushFailure( message, null, 'No exception was thrown.' );
646 | }
647 | }
648 | };
649 |
650 | /**
651 | * @deprecate since 1.8.0
652 | * Kept assertion helpers in root for backwards compatibility.
653 | */
654 | extend( QUnit, assert );
655 |
656 | /**
657 | * @deprecated since 1.9.0
658 | * Kept root "raises()" for backwards compatibility.
659 | * (Note that we don't introduce assert.raises).
660 | */
661 | QUnit.raises = assert[ "throws" ];
662 |
663 | /**
664 | * @deprecated since 1.0.0, replaced with error pushes since 1.3.0
665 | * Kept to avoid TypeErrors for undefined methods.
666 | */
667 | QUnit.equals = function() {
668 | QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" );
669 | };
670 | QUnit.same = function() {
671 | QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" );
672 | };
673 |
674 | // We want access to the constructor's prototype
675 | (function() {
676 | function F() {}
677 | F.prototype = QUnit;
678 | QUnit = new F();
679 | // Make F QUnit's constructor so that we can add to the prototype later
680 | QUnit.constructor = F;
681 | }());
682 |
683 | /**
684 | * Config object: Maintain internal state
685 | * Later exposed as QUnit.config
686 | * `config` initialized at top of scope
687 | */
688 | config = {
689 | // The queue of tests to run
690 | queue: [],
691 |
692 | // block until document ready
693 | blocking: true,
694 |
695 | // when enabled, show only failing tests
696 | // gets persisted through sessionStorage and can be changed in UI via checkbox
697 | hidepassed: false,
698 |
699 | // by default, run previously failed tests first
700 | // very useful in combination with "Hide passed tests" checked
701 | reorder: true,
702 |
703 | // by default, modify document.title when suite is done
704 | altertitle: true,
705 |
706 | // when enabled, all tests must call expect()
707 | requireExpects: false,
708 |
709 | // add checkboxes that are persisted in the query-string
710 | // when enabled, the id is set to `true` as a `QUnit.config` property
711 | urlConfig: [
712 | {
713 | id: "noglobals",
714 | label: "Check for Globals",
715 | tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings."
716 | },
717 | {
718 | id: "notrycatch",
719 | label: "No try-catch",
720 | tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings."
721 | }
722 | ],
723 |
724 | // Set of all modules.
725 | modules: {},
726 |
727 | // logging callback queues
728 | begin: [],
729 | done: [],
730 | log: [],
731 | testStart: [],
732 | testDone: [],
733 | moduleStart: [],
734 | moduleDone: []
735 | };
736 |
737 | // Export global variables, unless an 'exports' object exists,
738 | // in that case we assume we're in CommonJS (dealt with on the bottom of the script)
739 | if ( typeof exports === "undefined" ) {
740 | extend( window, QUnit );
741 |
742 | // Expose QUnit object
743 | window.QUnit = QUnit;
744 | }
745 |
746 | // Initialize more QUnit.config and QUnit.urlParams
747 | (function() {
748 | var i,
749 | location = window.location || { search: "", protocol: "file:" },
750 | params = location.search.slice( 1 ).split( "&" ),
751 | length = params.length,
752 | urlParams = {},
753 | current;
754 |
755 | if ( params[ 0 ] ) {
756 | for ( i = 0; i < length; i++ ) {
757 | current = params[ i ].split( "=" );
758 | current[ 0 ] = decodeURIComponent( current[ 0 ] );
759 | // allow just a key to turn on a flag, e.g., test.html?noglobals
760 | current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
761 | urlParams[ current[ 0 ] ] = current[ 1 ];
762 | }
763 | }
764 |
765 | QUnit.urlParams = urlParams;
766 |
767 | // String search anywhere in moduleName+testName
768 | config.filter = urlParams.filter;
769 |
770 | // Exact match of the module name
771 | config.module = urlParams.module;
772 |
773 | config.testNumber = parseInt( urlParams.testNumber, 10 ) || null;
774 |
775 | // Figure out if we're running the tests from a server or not
776 | QUnit.isLocal = location.protocol === "file:";
777 | }());
778 |
779 | // Extend QUnit object,
780 | // these after set here because they should not be exposed as global functions
781 | extend( QUnit, {
782 | assert: assert,
783 |
784 | config: config,
785 |
786 | // Initialize the configuration options
787 | init: function() {
788 | extend( config, {
789 | stats: { all: 0, bad: 0 },
790 | moduleStats: { all: 0, bad: 0 },
791 | started: +new Date(),
792 | updateRate: 1000,
793 | blocking: false,
794 | autostart: true,
795 | autorun: false,
796 | filter: "",
797 | queue: [],
798 | semaphore: 1
799 | });
800 |
801 | var tests, banner, result,
802 | qunit = id( "qunit" );
803 |
804 | if ( qunit ) {
805 | qunit.innerHTML =
806 | "" +
807 | "" +
808 | "" +
809 | "" +
810 | "
";
811 | }
812 |
813 | tests = id( "qunit-tests" );
814 | banner = id( "qunit-banner" );
815 | result = id( "qunit-testresult" );
816 |
817 | if ( tests ) {
818 | tests.innerHTML = "";
819 | }
820 |
821 | if ( banner ) {
822 | banner.className = "";
823 | }
824 |
825 | if ( result ) {
826 | result.parentNode.removeChild( result );
827 | }
828 |
829 | if ( tests ) {
830 | result = document.createElement( "p" );
831 | result.id = "qunit-testresult";
832 | result.className = "result";
833 | tests.parentNode.insertBefore( result, tests );
834 | result.innerHTML = "Running...
";
835 | }
836 | },
837 |
838 | // Resets the test setup. Useful for tests that modify the DOM.
839 | reset: function() {
840 | var fixture = id( "qunit-fixture" );
841 | if ( fixture ) {
842 | fixture.innerHTML = config.fixture;
843 | }
844 | },
845 |
846 | // Trigger an event on an element.
847 | // @example triggerEvent( document.body, "click" );
848 | triggerEvent: function( elem, type, event ) {
849 | if ( document.createEvent ) {
850 | event = document.createEvent( "MouseEvents" );
851 | event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
852 | 0, 0, 0, 0, 0, false, false, false, false, 0, null);
853 |
854 | elem.dispatchEvent( event );
855 | } else if ( elem.fireEvent ) {
856 | elem.fireEvent( "on" + type );
857 | }
858 | },
859 |
860 | // Safe object type checking
861 | is: function( type, obj ) {
862 | return QUnit.objectType( obj ) === type;
863 | },
864 |
865 | objectType: function( obj ) {
866 | if ( typeof obj === "undefined" ) {
867 | return "undefined";
868 | // consider: typeof null === object
869 | }
870 | if ( obj === null ) {
871 | return "null";
872 | }
873 |
874 | var match = toString.call( obj ).match(/^\[object\s(.*)\]$/),
875 | type = match && match[1] || "";
876 |
877 | switch ( type ) {
878 | case "Number":
879 | if ( isNaN(obj) ) {
880 | return "nan";
881 | }
882 | return "number";
883 | case "String":
884 | case "Boolean":
885 | case "Array":
886 | case "Date":
887 | case "RegExp":
888 | case "Function":
889 | return type.toLowerCase();
890 | }
891 | if ( typeof obj === "object" ) {
892 | return "object";
893 | }
894 | return undefined;
895 | },
896 |
897 | push: function( result, actual, expected, message ) {
898 | if ( !config.current ) {
899 | throw new Error( "assertion outside test context, was " + sourceFromStacktrace() );
900 | }
901 |
902 | var output, source,
903 | details = {
904 | module: config.current.module,
905 | name: config.current.testName,
906 | result: result,
907 | message: message,
908 | actual: actual,
909 | expected: expected
910 | };
911 |
912 | message = escapeText( message ) || ( result ? "okay" : "failed" );
913 | message = "" + message + "";
914 | output = message;
915 |
916 | if ( !result ) {
917 | expected = escapeText( QUnit.jsDump.parse(expected) );
918 | actual = escapeText( QUnit.jsDump.parse(actual) );
919 | output += "| Expected: | " + expected + " |
";
920 |
921 | if ( actual !== expected ) {
922 | output += "| Result: | " + actual + " |
";
923 | output += "| Diff: | " + QUnit.diff( expected, actual ) + " |
";
924 | }
925 |
926 | source = sourceFromStacktrace();
927 |
928 | if ( source ) {
929 | details.source = source;
930 | output += "| Source: | " + escapeText( source ) + " |
";
931 | }
932 |
933 | output += "
";
934 | }
935 |
936 | runLoggingCallbacks( "log", QUnit, details );
937 |
938 | config.current.assertions.push({
939 | result: !!result,
940 | message: output
941 | });
942 | },
943 |
944 | pushFailure: function( message, source, actual ) {
945 | if ( !config.current ) {
946 | throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) );
947 | }
948 |
949 | var output,
950 | details = {
951 | module: config.current.module,
952 | name: config.current.testName,
953 | result: false,
954 | message: message
955 | };
956 |
957 | message = escapeText( message ) || "error";
958 | message = "" + message + "";
959 | output = message;
960 |
961 | output += "";
962 |
963 | if ( actual ) {
964 | output += "| Result: | " + escapeText( actual ) + " |
";
965 | }
966 |
967 | if ( source ) {
968 | details.source = source;
969 | output += "| Source: | " + escapeText( source ) + " |
";
970 | }
971 |
972 | output += "
";
973 |
974 | runLoggingCallbacks( "log", QUnit, details );
975 |
976 | config.current.assertions.push({
977 | result: false,
978 | message: output
979 | });
980 | },
981 |
982 | url: function( params ) {
983 | params = extend( extend( {}, QUnit.urlParams ), params );
984 | var key,
985 | querystring = "?";
986 |
987 | for ( key in params ) {
988 | if ( !hasOwn.call( params, key ) ) {
989 | continue;
990 | }
991 | querystring += encodeURIComponent( key ) + "=" +
992 | encodeURIComponent( params[ key ] ) + "&";
993 | }
994 | return window.location.protocol + "//" + window.location.host +
995 | window.location.pathname + querystring.slice( 0, -1 );
996 | },
997 |
998 | extend: extend,
999 | id: id,
1000 | addEvent: addEvent
1001 | // load, equiv, jsDump, diff: Attached later
1002 | });
1003 |
1004 | /**
1005 | * @deprecated: Created for backwards compatibility with test runner that set the hook function
1006 | * into QUnit.{hook}, instead of invoking it and passing the hook function.
1007 | * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here.
1008 | * Doing this allows us to tell if the following methods have been overwritten on the actual
1009 | * QUnit object.
1010 | */
1011 | extend( QUnit.constructor.prototype, {
1012 |
1013 | // Logging callbacks; all receive a single argument with the listed properties
1014 | // run test/logs.html for any related changes
1015 | begin: registerLoggingCallback( "begin" ),
1016 |
1017 | // done: { failed, passed, total, runtime }
1018 | done: registerLoggingCallback( "done" ),
1019 |
1020 | // log: { result, actual, expected, message }
1021 | log: registerLoggingCallback( "log" ),
1022 |
1023 | // testStart: { name }
1024 | testStart: registerLoggingCallback( "testStart" ),
1025 |
1026 | // testDone: { name, failed, passed, total, duration }
1027 | testDone: registerLoggingCallback( "testDone" ),
1028 |
1029 | // moduleStart: { name }
1030 | moduleStart: registerLoggingCallback( "moduleStart" ),
1031 |
1032 | // moduleDone: { name, failed, passed, total }
1033 | moduleDone: registerLoggingCallback( "moduleDone" )
1034 | });
1035 |
1036 | if ( typeof document === "undefined" || document.readyState === "complete" ) {
1037 | config.autorun = true;
1038 | }
1039 |
1040 | QUnit.load = function() {
1041 | runLoggingCallbacks( "begin", QUnit, {} );
1042 |
1043 | // Initialize the config, saving the execution queue
1044 | var banner, filter, i, label, len, main, ol, toolbar, userAgent, val,
1045 | urlConfigCheckboxesContainer, urlConfigCheckboxes, moduleFilter,
1046 | numModules = 0,
1047 | moduleFilterHtml = "",
1048 | urlConfigHtml = "",
1049 | oldconfig = extend( {}, config );
1050 |
1051 | QUnit.init();
1052 | extend(config, oldconfig);
1053 |
1054 | config.blocking = false;
1055 |
1056 | len = config.urlConfig.length;
1057 |
1058 | for ( i = 0; i < len; i++ ) {
1059 | val = config.urlConfig[i];
1060 | if ( typeof val === "string" ) {
1061 | val = {
1062 | id: val,
1063 | label: val,
1064 | tooltip: "[no tooltip available]"
1065 | };
1066 | }
1067 | config[ val.id ] = QUnit.urlParams[ val.id ];
1068 | urlConfigHtml += "";
1074 | }
1075 |
1076 | moduleFilterHtml += "";
1089 |
1090 | // `userAgent` initialized at top of scope
1091 | userAgent = id( "qunit-userAgent" );
1092 | if ( userAgent ) {
1093 | userAgent.innerHTML = navigator.userAgent;
1094 | }
1095 |
1096 | // `banner` initialized at top of scope
1097 | banner = id( "qunit-header" );
1098 | if ( banner ) {
1099 | banner.innerHTML = "" + banner.innerHTML + " ";
1100 | }
1101 |
1102 | // `toolbar` initialized at top of scope
1103 | toolbar = id( "qunit-testrunner-toolbar" );
1104 | if ( toolbar ) {
1105 | // `filter` initialized at top of scope
1106 | filter = document.createElement( "input" );
1107 | filter.type = "checkbox";
1108 | filter.id = "qunit-filter-pass";
1109 |
1110 | addEvent( filter, "click", function() {
1111 | var tmp,
1112 | ol = document.getElementById( "qunit-tests" );
1113 |
1114 | if ( filter.checked ) {
1115 | ol.className = ol.className + " hidepass";
1116 | } else {
1117 | tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
1118 | ol.className = tmp.replace( / hidepass /, " " );
1119 | }
1120 | if ( defined.sessionStorage ) {
1121 | if (filter.checked) {
1122 | sessionStorage.setItem( "qunit-filter-passed-tests", "true" );
1123 | } else {
1124 | sessionStorage.removeItem( "qunit-filter-passed-tests" );
1125 | }
1126 | }
1127 | });
1128 |
1129 | if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) {
1130 | filter.checked = true;
1131 | // `ol` initialized at top of scope
1132 | ol = document.getElementById( "qunit-tests" );
1133 | ol.className = ol.className + " hidepass";
1134 | }
1135 | toolbar.appendChild( filter );
1136 |
1137 | // `label` initialized at top of scope
1138 | label = document.createElement( "label" );
1139 | label.setAttribute( "for", "qunit-filter-pass" );
1140 | label.setAttribute( "title", "Only show tests and assertons that fail. Stored in sessionStorage." );
1141 | label.innerHTML = "Hide passed tests";
1142 | toolbar.appendChild( label );
1143 |
1144 | urlConfigCheckboxesContainer = document.createElement("span");
1145 | urlConfigCheckboxesContainer.innerHTML = urlConfigHtml;
1146 | urlConfigCheckboxes = urlConfigCheckboxesContainer.getElementsByTagName("input");
1147 | // For oldIE support:
1148 | // * Add handlers to the individual elements instead of the container
1149 | // * Use "click" instead of "change"
1150 | // * Fallback from event.target to event.srcElement
1151 | addEvents( urlConfigCheckboxes, "click", function( event ) {
1152 | var params = {},
1153 | target = event.target || event.srcElement;
1154 | params[ target.name ] = target.checked ? true : undefined;
1155 | window.location = QUnit.url( params );
1156 | });
1157 | toolbar.appendChild( urlConfigCheckboxesContainer );
1158 |
1159 | if (numModules > 1) {
1160 | moduleFilter = document.createElement( 'span' );
1161 | moduleFilter.setAttribute( 'id', 'qunit-modulefilter-container' );
1162 | moduleFilter.innerHTML = moduleFilterHtml;
1163 | addEvent( moduleFilter.lastChild, "change", function() {
1164 | var selectBox = moduleFilter.getElementsByTagName("select")[0],
1165 | selectedModule = decodeURIComponent(selectBox.options[selectBox.selectedIndex].value);
1166 |
1167 | window.location = QUnit.url( { module: ( selectedModule === "" ) ? undefined : selectedModule } );
1168 | });
1169 | toolbar.appendChild(moduleFilter);
1170 | }
1171 | }
1172 |
1173 | // `main` initialized at top of scope
1174 | main = id( "qunit-fixture" );
1175 | if ( main ) {
1176 | config.fixture = main.innerHTML;
1177 | }
1178 |
1179 | if ( config.autostart ) {
1180 | QUnit.start();
1181 | }
1182 | };
1183 |
1184 | addEvent( window, "load", QUnit.load );
1185 |
1186 | // `onErrorFnPrev` initialized at top of scope
1187 | // Preserve other handlers
1188 | onErrorFnPrev = window.onerror;
1189 |
1190 | // Cover uncaught exceptions
1191 | // Returning true will surpress the default browser handler,
1192 | // returning false will let it run.
1193 | window.onerror = function ( error, filePath, linerNr ) {
1194 | var ret = false;
1195 | if ( onErrorFnPrev ) {
1196 | ret = onErrorFnPrev( error, filePath, linerNr );
1197 | }
1198 |
1199 | // Treat return value as window.onerror itself does,
1200 | // Only do our handling if not surpressed.
1201 | if ( ret !== true ) {
1202 | if ( QUnit.config.current ) {
1203 | if ( QUnit.config.current.ignoreGlobalErrors ) {
1204 | return true;
1205 | }
1206 | QUnit.pushFailure( error, filePath + ":" + linerNr );
1207 | } else {
1208 | QUnit.test( "global failure", extend( function() {
1209 | QUnit.pushFailure( error, filePath + ":" + linerNr );
1210 | }, { validTest: validTest } ) );
1211 | }
1212 | return false;
1213 | }
1214 |
1215 | return ret;
1216 | };
1217 |
1218 | function done() {
1219 | config.autorun = true;
1220 |
1221 | // Log the last module results
1222 | if ( config.currentModule ) {
1223 | runLoggingCallbacks( "moduleDone", QUnit, {
1224 | name: config.currentModule,
1225 | failed: config.moduleStats.bad,
1226 | passed: config.moduleStats.all - config.moduleStats.bad,
1227 | total: config.moduleStats.all
1228 | });
1229 | }
1230 |
1231 | var i, key,
1232 | banner = id( "qunit-banner" ),
1233 | tests = id( "qunit-tests" ),
1234 | runtime = +new Date() - config.started,
1235 | passed = config.stats.all - config.stats.bad,
1236 | html = [
1237 | "Tests completed in ",
1238 | runtime,
1239 | " milliseconds.
",
1240 | "",
1241 | passed,
1242 | " assertions of ",
1243 | config.stats.all,
1244 | " passed, ",
1245 | config.stats.bad,
1246 | " failed."
1247 | ].join( "" );
1248 |
1249 | if ( banner ) {
1250 | banner.className = ( config.stats.bad ? "qunit-fail" : "qunit-pass" );
1251 | }
1252 |
1253 | if ( tests ) {
1254 | id( "qunit-testresult" ).innerHTML = html;
1255 | }
1256 |
1257 | if ( config.altertitle && typeof document !== "undefined" && document.title ) {
1258 | // show ✖ for good, ✔ for bad suite result in title
1259 | // use escape sequences in case file gets loaded with non-utf-8-charset
1260 | document.title = [
1261 | ( config.stats.bad ? "\u2716" : "\u2714" ),
1262 | document.title.replace( /^[\u2714\u2716] /i, "" )
1263 | ].join( " " );
1264 | }
1265 |
1266 | // clear own sessionStorage items if all tests passed
1267 | if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) {
1268 | // `key` & `i` initialized at top of scope
1269 | for ( i = 0; i < sessionStorage.length; i++ ) {
1270 | key = sessionStorage.key( i++ );
1271 | if ( key.indexOf( "qunit-test-" ) === 0 ) {
1272 | sessionStorage.removeItem( key );
1273 | }
1274 | }
1275 | }
1276 |
1277 | // scroll back to top to show results
1278 | if ( window.scrollTo ) {
1279 | window.scrollTo(0, 0);
1280 | }
1281 |
1282 | runLoggingCallbacks( "done", QUnit, {
1283 | failed: config.stats.bad,
1284 | passed: passed,
1285 | total: config.stats.all,
1286 | runtime: runtime
1287 | });
1288 | }
1289 |
1290 | /** @return Boolean: true if this test should be ran */
1291 | function validTest( test ) {
1292 | var include,
1293 | filter = config.filter && config.filter.toLowerCase(),
1294 | module = config.module && config.module.toLowerCase(),
1295 | fullName = (test.module + ": " + test.testName).toLowerCase();
1296 |
1297 | // Internally-generated tests are always valid
1298 | if ( test.callback && test.callback.validTest === validTest ) {
1299 | delete test.callback.validTest;
1300 | return true;
1301 | }
1302 |
1303 | if ( config.testNumber ) {
1304 | return test.testNumber === config.testNumber;
1305 | }
1306 |
1307 | if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) {
1308 | return false;
1309 | }
1310 |
1311 | if ( !filter ) {
1312 | return true;
1313 | }
1314 |
1315 | include = filter.charAt( 0 ) !== "!";
1316 | if ( !include ) {
1317 | filter = filter.slice( 1 );
1318 | }
1319 |
1320 | // If the filter matches, we need to honour include
1321 | if ( fullName.indexOf( filter ) !== -1 ) {
1322 | return include;
1323 | }
1324 |
1325 | // Otherwise, do the opposite
1326 | return !include;
1327 | }
1328 |
1329 | // so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions)
1330 | // Later Safari and IE10 are supposed to support error.stack as well
1331 | // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
1332 | function extractStacktrace( e, offset ) {
1333 | offset = offset === undefined ? 3 : offset;
1334 |
1335 | var stack, include, i;
1336 |
1337 | if ( e.stacktrace ) {
1338 | // Opera
1339 | return e.stacktrace.split( "\n" )[ offset + 3 ];
1340 | } else if ( e.stack ) {
1341 | // Firefox, Chrome
1342 | stack = e.stack.split( "\n" );
1343 | if (/^error$/i.test( stack[0] ) ) {
1344 | stack.shift();
1345 | }
1346 | if ( fileName ) {
1347 | include = [];
1348 | for ( i = offset; i < stack.length; i++ ) {
1349 | if ( stack[ i ].indexOf( fileName ) !== -1 ) {
1350 | break;
1351 | }
1352 | include.push( stack[ i ] );
1353 | }
1354 | if ( include.length ) {
1355 | return include.join( "\n" );
1356 | }
1357 | }
1358 | return stack[ offset ];
1359 | } else if ( e.sourceURL ) {
1360 | // Safari, PhantomJS
1361 | // hopefully one day Safari provides actual stacktraces
1362 | // exclude useless self-reference for generated Error objects
1363 | if ( /qunit.js$/.test( e.sourceURL ) ) {
1364 | return;
1365 | }
1366 | // for actual exceptions, this is useful
1367 | return e.sourceURL + ":" + e.line;
1368 | }
1369 | }
1370 | function sourceFromStacktrace( offset ) {
1371 | try {
1372 | throw new Error();
1373 | } catch ( e ) {
1374 | return extractStacktrace( e, offset );
1375 | }
1376 | }
1377 |
1378 | /**
1379 | * Escape text for attribute or text content.
1380 | */
1381 | function escapeText( s ) {
1382 | if ( !s ) {
1383 | return "";
1384 | }
1385 | s = s + "";
1386 | // Both single quotes and double quotes (for attributes)
1387 | return s.replace( /['"<>&]/g, function( s ) {
1388 | switch( s ) {
1389 | case '\'':
1390 | return ''';
1391 | case '"':
1392 | return '"';
1393 | case '<':
1394 | return '<';
1395 | case '>':
1396 | return '>';
1397 | case '&':
1398 | return '&';
1399 | }
1400 | });
1401 | }
1402 |
1403 | function synchronize( callback, last ) {
1404 | config.queue.push( callback );
1405 |
1406 | if ( config.autorun && !config.blocking ) {
1407 | process( last );
1408 | }
1409 | }
1410 |
1411 | function process( last ) {
1412 | function next() {
1413 | process( last );
1414 | }
1415 | var start = new Date().getTime();
1416 | config.depth = config.depth ? config.depth + 1 : 1;
1417 |
1418 | while ( config.queue.length && !config.blocking ) {
1419 | if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
1420 | config.queue.shift()();
1421 | } else {
1422 | window.setTimeout( next, 13 );
1423 | break;
1424 | }
1425 | }
1426 | config.depth--;
1427 | if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
1428 | done();
1429 | }
1430 | }
1431 |
1432 | function saveGlobal() {
1433 | config.pollution = [];
1434 |
1435 | if ( config.noglobals ) {
1436 | for ( var key in window ) {
1437 | // in Opera sometimes DOM element ids show up here, ignore them
1438 | if ( !hasOwn.call( window, key ) || /^qunit-test-output/.test( key ) ) {
1439 | continue;
1440 | }
1441 | config.pollution.push( key );
1442 | }
1443 | }
1444 | }
1445 |
1446 | function checkPollution() {
1447 | var newGlobals,
1448 | deletedGlobals,
1449 | old = config.pollution;
1450 |
1451 | saveGlobal();
1452 |
1453 | newGlobals = diff( config.pollution, old );
1454 | if ( newGlobals.length > 0 ) {
1455 | QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") );
1456 | }
1457 |
1458 | deletedGlobals = diff( old, config.pollution );
1459 | if ( deletedGlobals.length > 0 ) {
1460 | QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") );
1461 | }
1462 | }
1463 |
1464 | // returns a new Array with the elements that are in a but not in b
1465 | function diff( a, b ) {
1466 | var i, j,
1467 | result = a.slice();
1468 |
1469 | for ( i = 0; i < result.length; i++ ) {
1470 | for ( j = 0; j < b.length; j++ ) {
1471 | if ( result[i] === b[j] ) {
1472 | result.splice( i, 1 );
1473 | i--;
1474 | break;
1475 | }
1476 | }
1477 | }
1478 | return result;
1479 | }
1480 |
1481 | function extend( a, b ) {
1482 | for ( var prop in b ) {
1483 | if ( b[ prop ] === undefined ) {
1484 | delete a[ prop ];
1485 |
1486 | // Avoid "Member not found" error in IE8 caused by setting window.constructor
1487 | } else if ( prop !== "constructor" || a !== window ) {
1488 | a[ prop ] = b[ prop ];
1489 | }
1490 | }
1491 |
1492 | return a;
1493 | }
1494 |
1495 | /**
1496 | * @param {HTMLElement} elem
1497 | * @param {string} type
1498 | * @param {Function} fn
1499 | */
1500 | function addEvent( elem, type, fn ) {
1501 | // Standards-based browsers
1502 | if ( elem.addEventListener ) {
1503 | elem.addEventListener( type, fn, false );
1504 | // IE
1505 | } else {
1506 | elem.attachEvent( "on" + type, fn );
1507 | }
1508 | }
1509 |
1510 | /**
1511 | * @param {Array|NodeList} elems
1512 | * @param {string} type
1513 | * @param {Function} fn
1514 | */
1515 | function addEvents( elems, type, fn ) {
1516 | var i = elems.length;
1517 | while ( i-- ) {
1518 | addEvent( elems[i], type, fn );
1519 | }
1520 | }
1521 |
1522 | function hasClass( elem, name ) {
1523 | return (" " + elem.className + " ").indexOf(" " + name + " ") > -1;
1524 | }
1525 |
1526 | function addClass( elem, name ) {
1527 | if ( !hasClass( elem, name ) ) {
1528 | elem.className += (elem.className ? " " : "") + name;
1529 | }
1530 | }
1531 |
1532 | function removeClass( elem, name ) {
1533 | var set = " " + elem.className + " ";
1534 | // Class name may appear multiple times
1535 | while ( set.indexOf(" " + name + " ") > -1 ) {
1536 | set = set.replace(" " + name + " " , " ");
1537 | }
1538 | // If possible, trim it for prettiness, but not neccecarily
1539 | elem.className = window.jQuery ? jQuery.trim( set ) : ( set.trim ? set.trim() : set );
1540 | }
1541 |
1542 | function id( name ) {
1543 | return !!( typeof document !== "undefined" && document && document.getElementById ) &&
1544 | document.getElementById( name );
1545 | }
1546 |
1547 | function registerLoggingCallback( key ) {
1548 | return function( callback ) {
1549 | config[key].push( callback );
1550 | };
1551 | }
1552 |
1553 | // Supports deprecated method of completely overwriting logging callbacks
1554 | function runLoggingCallbacks( key, scope, args ) {
1555 | var i, callbacks;
1556 | if ( QUnit.hasOwnProperty( key ) ) {
1557 | QUnit[ key ].call(scope, args );
1558 | } else {
1559 | callbacks = config[ key ];
1560 | for ( i = 0; i < callbacks.length; i++ ) {
1561 | callbacks[ i ].call( scope, args );
1562 | }
1563 | }
1564 | }
1565 |
1566 | // Test for equality any JavaScript type.
1567 | // Author: Philippe Rathé
1568 | QUnit.equiv = (function() {
1569 |
1570 | // Call the o related callback with the given arguments.
1571 | function bindCallbacks( o, callbacks, args ) {
1572 | var prop = QUnit.objectType( o );
1573 | if ( prop ) {
1574 | if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) {
1575 | return callbacks[ prop ].apply( callbacks, args );
1576 | } else {
1577 | return callbacks[ prop ]; // or undefined
1578 | }
1579 | }
1580 | }
1581 |
1582 | // the real equiv function
1583 | var innerEquiv,
1584 | // stack to decide between skip/abort functions
1585 | callers = [],
1586 | // stack to avoiding loops from circular referencing
1587 | parents = [],
1588 |
1589 | getProto = Object.getPrototypeOf || function ( obj ) {
1590 | return obj.__proto__;
1591 | },
1592 | callbacks = (function () {
1593 |
1594 | // for string, boolean, number and null
1595 | function useStrictEquality( b, a ) {
1596 | /*jshint eqeqeq:false */
1597 | if ( b instanceof a.constructor || a instanceof b.constructor ) {
1598 | // to catch short annotaion VS 'new' annotation of a
1599 | // declaration
1600 | // e.g. var i = 1;
1601 | // var j = new Number(1);
1602 | return a == b;
1603 | } else {
1604 | return a === b;
1605 | }
1606 | }
1607 |
1608 | return {
1609 | "string": useStrictEquality,
1610 | "boolean": useStrictEquality,
1611 | "number": useStrictEquality,
1612 | "null": useStrictEquality,
1613 | "undefined": useStrictEquality,
1614 |
1615 | "nan": function( b ) {
1616 | return isNaN( b );
1617 | },
1618 |
1619 | "date": function( b, a ) {
1620 | return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf();
1621 | },
1622 |
1623 | "regexp": function( b, a ) {
1624 | return QUnit.objectType( b ) === "regexp" &&
1625 | // the regex itself
1626 | a.source === b.source &&
1627 | // and its modifers
1628 | a.global === b.global &&
1629 | // (gmi) ...
1630 | a.ignoreCase === b.ignoreCase &&
1631 | a.multiline === b.multiline &&
1632 | a.sticky === b.sticky;
1633 | },
1634 |
1635 | // - skip when the property is a method of an instance (OOP)
1636 | // - abort otherwise,
1637 | // initial === would have catch identical references anyway
1638 | "function": function() {
1639 | var caller = callers[callers.length - 1];
1640 | return caller !== Object && typeof caller !== "undefined";
1641 | },
1642 |
1643 | "array": function( b, a ) {
1644 | var i, j, len, loop;
1645 |
1646 | // b could be an object literal here
1647 | if ( QUnit.objectType( b ) !== "array" ) {
1648 | return false;
1649 | }
1650 |
1651 | len = a.length;
1652 | if ( len !== b.length ) {
1653 | // safe and faster
1654 | return false;
1655 | }
1656 |
1657 | // track reference to avoid circular references
1658 | parents.push( a );
1659 | for ( i = 0; i < len; i++ ) {
1660 | loop = false;
1661 | for ( j = 0; j < parents.length; j++ ) {
1662 | if ( parents[j] === a[i] ) {
1663 | loop = true;// dont rewalk array
1664 | }
1665 | }
1666 | if ( !loop && !innerEquiv(a[i], b[i]) ) {
1667 | parents.pop();
1668 | return false;
1669 | }
1670 | }
1671 | parents.pop();
1672 | return true;
1673 | },
1674 |
1675 | "object": function( b, a ) {
1676 | var i, j, loop,
1677 | // Default to true
1678 | eq = true,
1679 | aProperties = [],
1680 | bProperties = [];
1681 |
1682 | // comparing constructors is more strict than using
1683 | // instanceof
1684 | if ( a.constructor !== b.constructor ) {
1685 | // Allow objects with no prototype to be equivalent to
1686 | // objects with Object as their constructor.
1687 | if ( !(( getProto(a) === null && getProto(b) === Object.prototype ) ||
1688 | ( getProto(b) === null && getProto(a) === Object.prototype ) ) ) {
1689 | return false;
1690 | }
1691 | }
1692 |
1693 | // stack constructor before traversing properties
1694 | callers.push( a.constructor );
1695 | // track reference to avoid circular references
1696 | parents.push( a );
1697 |
1698 | for ( i in a ) { // be strict: don't ensures hasOwnProperty
1699 | // and go deep
1700 | loop = false;
1701 | for ( j = 0; j < parents.length; j++ ) {
1702 | if ( parents[j] === a[i] ) {
1703 | // don't go down the same path twice
1704 | loop = true;
1705 | }
1706 | }
1707 | aProperties.push(i); // collect a's properties
1708 |
1709 | if (!loop && !innerEquiv( a[i], b[i] ) ) {
1710 | eq = false;
1711 | break;
1712 | }
1713 | }
1714 |
1715 | callers.pop(); // unstack, we are done
1716 | parents.pop();
1717 |
1718 | for ( i in b ) {
1719 | bProperties.push( i ); // collect b's properties
1720 | }
1721 |
1722 | // Ensures identical properties name
1723 | return eq && innerEquiv( aProperties.sort(), bProperties.sort() );
1724 | }
1725 | };
1726 | }());
1727 |
1728 | innerEquiv = function() { // can take multiple arguments
1729 | var args = [].slice.apply( arguments );
1730 | if ( args.length < 2 ) {
1731 | return true; // end transition
1732 | }
1733 |
1734 | return (function( a, b ) {
1735 | if ( a === b ) {
1736 | return true; // catch the most you can
1737 | } else if ( a === null || b === null || typeof a === "undefined" ||
1738 | typeof b === "undefined" ||
1739 | QUnit.objectType(a) !== QUnit.objectType(b) ) {
1740 | return false; // don't lose time with error prone cases
1741 | } else {
1742 | return bindCallbacks(a, callbacks, [ b, a ]);
1743 | }
1744 |
1745 | // apply transition with (1..n) arguments
1746 | }( args[0], args[1] ) && arguments.callee.apply( this, args.splice(1, args.length - 1 )) );
1747 | };
1748 |
1749 | return innerEquiv;
1750 | }());
1751 |
1752 | /**
1753 | * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
1754 | * http://flesler.blogspot.com Licensed under BSD
1755 | * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008
1756 | *
1757 | * @projectDescription Advanced and extensible data dumping for Javascript.
1758 | * @version 1.0.0
1759 | * @author Ariel Flesler
1760 | * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
1761 | */
1762 | QUnit.jsDump = (function() {
1763 | function quote( str ) {
1764 | return '"' + str.toString().replace( /"/g, '\\"' ) + '"';
1765 | }
1766 | function literal( o ) {
1767 | return o + "";
1768 | }
1769 | function join( pre, arr, post ) {
1770 | var s = jsDump.separator(),
1771 | base = jsDump.indent(),
1772 | inner = jsDump.indent(1);
1773 | if ( arr.join ) {
1774 | arr = arr.join( "," + s + inner );
1775 | }
1776 | if ( !arr ) {
1777 | return pre + post;
1778 | }
1779 | return [ pre, inner + arr, base + post ].join(s);
1780 | }
1781 | function array( arr, stack ) {
1782 | var i = arr.length, ret = new Array(i);
1783 | this.up();
1784 | while ( i-- ) {
1785 | ret[i] = this.parse( arr[i] , undefined , stack);
1786 | }
1787 | this.down();
1788 | return join( "[", ret, "]" );
1789 | }
1790 |
1791 | var reName = /^function (\w+)/,
1792 | jsDump = {
1793 | // type is used mostly internally, you can fix a (custom)type in advance
1794 | parse: function( obj, type, stack ) {
1795 | stack = stack || [ ];
1796 | var inStack, res,
1797 | parser = this.parsers[ type || this.typeOf(obj) ];
1798 |
1799 | type = typeof parser;
1800 | inStack = inArray( obj, stack );
1801 |
1802 | if ( inStack !== -1 ) {
1803 | return "recursion(" + (inStack - stack.length) + ")";
1804 | }
1805 | if ( type === "function" ) {
1806 | stack.push( obj );
1807 | res = parser.call( this, obj, stack );
1808 | stack.pop();
1809 | return res;
1810 | }
1811 | return ( type === "string" ) ? parser : this.parsers.error;
1812 | },
1813 | typeOf: function( obj ) {
1814 | var type;
1815 | if ( obj === null ) {
1816 | type = "null";
1817 | } else if ( typeof obj === "undefined" ) {
1818 | type = "undefined";
1819 | } else if ( QUnit.is( "regexp", obj) ) {
1820 | type = "regexp";
1821 | } else if ( QUnit.is( "date", obj) ) {
1822 | type = "date";
1823 | } else if ( QUnit.is( "function", obj) ) {
1824 | type = "function";
1825 | } else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) {
1826 | type = "window";
1827 | } else if ( obj.nodeType === 9 ) {
1828 | type = "document";
1829 | } else if ( obj.nodeType ) {
1830 | type = "node";
1831 | } else if (
1832 | // native arrays
1833 | toString.call( obj ) === "[object Array]" ||
1834 | // NodeList objects
1835 | ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) )
1836 | ) {
1837 | type = "array";
1838 | } else if ( obj.constructor === Error.prototype.constructor ) {
1839 | type = "error";
1840 | } else {
1841 | type = typeof obj;
1842 | }
1843 | return type;
1844 | },
1845 | separator: function() {
1846 | return this.multiline ? this.HTML ? "
" : "\n" : this.HTML ? " " : " ";
1847 | },
1848 | // extra can be a number, shortcut for increasing-calling-decreasing
1849 | indent: function( extra ) {
1850 | if ( !this.multiline ) {
1851 | return "";
1852 | }
1853 | var chr = this.indentChar;
1854 | if ( this.HTML ) {
1855 | chr = chr.replace( /\t/g, " " ).replace( / /g, " " );
1856 | }
1857 | return new Array( this._depth_ + (extra||0) ).join(chr);
1858 | },
1859 | up: function( a ) {
1860 | this._depth_ += a || 1;
1861 | },
1862 | down: function( a ) {
1863 | this._depth_ -= a || 1;
1864 | },
1865 | setParser: function( name, parser ) {
1866 | this.parsers[name] = parser;
1867 | },
1868 | // The next 3 are exposed so you can use them
1869 | quote: quote,
1870 | literal: literal,
1871 | join: join,
1872 | //
1873 | _depth_: 1,
1874 | // This is the list of parsers, to modify them, use jsDump.setParser
1875 | parsers: {
1876 | window: "[Window]",
1877 | document: "[Document]",
1878 | error: function(error) {
1879 | return "Error(\"" + error.message + "\")";
1880 | },
1881 | unknown: "[Unknown]",
1882 | "null": "null",
1883 | "undefined": "undefined",
1884 | "function": function( fn ) {
1885 | var ret = "function",
1886 | // functions never have name in IE
1887 | name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];
1888 |
1889 | if ( name ) {
1890 | ret += " " + name;
1891 | }
1892 | ret += "( ";
1893 |
1894 | ret = [ ret, QUnit.jsDump.parse( fn, "functionArgs" ), "){" ].join( "" );
1895 | return join( ret, QUnit.jsDump.parse(fn,"functionCode" ), "}" );
1896 | },
1897 | array: array,
1898 | nodelist: array,
1899 | "arguments": array,
1900 | object: function( map, stack ) {
1901 | var ret = [ ], keys, key, val, i;
1902 | QUnit.jsDump.up();
1903 | keys = [];
1904 | for ( key in map ) {
1905 | keys.push( key );
1906 | }
1907 | keys.sort();
1908 | for ( i = 0; i < keys.length; i++ ) {
1909 | key = keys[ i ];
1910 | val = map[ key ];
1911 | ret.push( QUnit.jsDump.parse( key, "key" ) + ": " + QUnit.jsDump.parse( val, undefined, stack ) );
1912 | }
1913 | QUnit.jsDump.down();
1914 | return join( "{", ret, "}" );
1915 | },
1916 | node: function( node ) {
1917 | var len, i, val,
1918 | open = QUnit.jsDump.HTML ? "<" : "<",
1919 | close = QUnit.jsDump.HTML ? ">" : ">",
1920 | tag = node.nodeName.toLowerCase(),
1921 | ret = open + tag,
1922 | attrs = node.attributes;
1923 |
1924 | if ( attrs ) {
1925 | for ( i = 0, len = attrs.length; i < len; i++ ) {
1926 | val = attrs[i].nodeValue;
1927 | // IE6 includes all attributes in .attributes, even ones not explicitly set.
1928 | // Those have values like undefined, null, 0, false, "" or "inherit".
1929 | if ( val && val !== "inherit" ) {
1930 | ret += " " + attrs[i].nodeName + "=" + QUnit.jsDump.parse( val, "attribute" );
1931 | }
1932 | }
1933 | }
1934 | ret += close;
1935 |
1936 | // Show content of TextNode or CDATASection
1937 | if ( node.nodeType === 3 || node.nodeType === 4 ) {
1938 | ret += node.nodeValue;
1939 | }
1940 |
1941 | return ret + open + "/" + tag + close;
1942 | },
1943 | // function calls it internally, it's the arguments part of the function
1944 | functionArgs: function( fn ) {
1945 | var args,
1946 | l = fn.length;
1947 |
1948 | if ( !l ) {
1949 | return "";
1950 | }
1951 |
1952 | args = new Array(l);
1953 | while ( l-- ) {
1954 | // 97 is 'a'
1955 | args[l] = String.fromCharCode(97+l);
1956 | }
1957 | return " " + args.join( ", " ) + " ";
1958 | },
1959 | // object calls it internally, the key part of an item in a map
1960 | key: quote,
1961 | // function calls it internally, it's the content of the function
1962 | functionCode: "[code]",
1963 | // node calls it internally, it's an html attribute value
1964 | attribute: quote,
1965 | string: quote,
1966 | date: quote,
1967 | regexp: literal,
1968 | number: literal,
1969 | "boolean": literal
1970 | },
1971 | // if true, entities are escaped ( <, >, \t, space and \n )
1972 | HTML: false,
1973 | // indentation unit
1974 | indentChar: " ",
1975 | // if true, items in a collection, are separated by a \n, else just a space.
1976 | multiline: true
1977 | };
1978 |
1979 | return jsDump;
1980 | }());
1981 |
1982 | // from jquery.js
1983 | function inArray( elem, array ) {
1984 | if ( array.indexOf ) {
1985 | return array.indexOf( elem );
1986 | }
1987 |
1988 | for ( var i = 0, length = array.length; i < length; i++ ) {
1989 | if ( array[ i ] === elem ) {
1990 | return i;
1991 | }
1992 | }
1993 |
1994 | return -1;
1995 | }
1996 |
1997 | /*
1998 | * Javascript Diff Algorithm
1999 | * By John Resig (http://ejohn.org/)
2000 | * Modified by Chu Alan "sprite"
2001 | *
2002 | * Released under the MIT license.
2003 | *
2004 | * More Info:
2005 | * http://ejohn.org/projects/javascript-diff-algorithm/
2006 | *
2007 | * Usage: QUnit.diff(expected, actual)
2008 | *
2009 | * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick brown fox jumped jumps over"
2010 | */
2011 | QUnit.diff = (function() {
2012 | /*jshint eqeqeq:false, eqnull:true */
2013 | function diff( o, n ) {
2014 | var i,
2015 | ns = {},
2016 | os = {};
2017 |
2018 | for ( i = 0; i < n.length; i++ ) {
2019 | if ( !hasOwn.call( ns, n[i] ) ) {
2020 | ns[ n[i] ] = {
2021 | rows: [],
2022 | o: null
2023 | };
2024 | }
2025 | ns[ n[i] ].rows.push( i );
2026 | }
2027 |
2028 | for ( i = 0; i < o.length; i++ ) {
2029 | if ( !hasOwn.call( os, o[i] ) ) {
2030 | os[ o[i] ] = {
2031 | rows: [],
2032 | n: null
2033 | };
2034 | }
2035 | os[ o[i] ].rows.push( i );
2036 | }
2037 |
2038 | for ( i in ns ) {
2039 | if ( !hasOwn.call( ns, i ) ) {
2040 | continue;
2041 | }
2042 | if ( ns[i].rows.length === 1 && hasOwn.call( os, i ) && os[i].rows.length === 1 ) {
2043 | n[ ns[i].rows[0] ] = {
2044 | text: n[ ns[i].rows[0] ],
2045 | row: os[i].rows[0]
2046 | };
2047 | o[ os[i].rows[0] ] = {
2048 | text: o[ os[i].rows[0] ],
2049 | row: ns[i].rows[0]
2050 | };
2051 | }
2052 | }
2053 |
2054 | for ( i = 0; i < n.length - 1; i++ ) {
2055 | if ( n[i].text != null && n[ i + 1 ].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null &&
2056 | n[ i + 1 ] == o[ n[i].row + 1 ] ) {
2057 |
2058 | n[ i + 1 ] = {
2059 | text: n[ i + 1 ],
2060 | row: n[i].row + 1
2061 | };
2062 | o[ n[i].row + 1 ] = {
2063 | text: o[ n[i].row + 1 ],
2064 | row: i + 1
2065 | };
2066 | }
2067 | }
2068 |
2069 | for ( i = n.length - 1; i > 0; i-- ) {
2070 | if ( n[i].text != null && n[ i - 1 ].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null &&
2071 | n[ i - 1 ] == o[ n[i].row - 1 ]) {
2072 |
2073 | n[ i - 1 ] = {
2074 | text: n[ i - 1 ],
2075 | row: n[i].row - 1
2076 | };
2077 | o[ n[i].row - 1 ] = {
2078 | text: o[ n[i].row - 1 ],
2079 | row: i - 1
2080 | };
2081 | }
2082 | }
2083 |
2084 | return {
2085 | o: o,
2086 | n: n
2087 | };
2088 | }
2089 |
2090 | return function( o, n ) {
2091 | o = o.replace( /\s+$/, "" );
2092 | n = n.replace( /\s+$/, "" );
2093 |
2094 | var i, pre,
2095 | str = "",
2096 | out = diff( o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/) ),
2097 | oSpace = o.match(/\s+/g),
2098 | nSpace = n.match(/\s+/g);
2099 |
2100 | if ( oSpace == null ) {
2101 | oSpace = [ " " ];
2102 | }
2103 | else {
2104 | oSpace.push( " " );
2105 | }
2106 |
2107 | if ( nSpace == null ) {
2108 | nSpace = [ " " ];
2109 | }
2110 | else {
2111 | nSpace.push( " " );
2112 | }
2113 |
2114 | if ( out.n.length === 0 ) {
2115 | for ( i = 0; i < out.o.length; i++ ) {
2116 | str += "" + out.o[i] + oSpace[i] + "";
2117 | }
2118 | }
2119 | else {
2120 | if ( out.n[0].text == null ) {
2121 | for ( n = 0; n < out.o.length && out.o[n].text == null; n++ ) {
2122 | str += "" + out.o[n] + oSpace[n] + "";
2123 | }
2124 | }
2125 |
2126 | for ( i = 0; i < out.n.length; i++ ) {
2127 | if (out.n[i].text == null) {
2128 | str += "" + out.n[i] + nSpace[i] + "";
2129 | }
2130 | else {
2131 | // `pre` initialized at top of scope
2132 | pre = "";
2133 |
2134 | for ( n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) {
2135 | pre += "" + out.o[n] + oSpace[n] + "";
2136 | }
2137 | str += " " + out.n[i].text + nSpace[i] + pre;
2138 | }
2139 | }
2140 | }
2141 |
2142 | return str;
2143 | };
2144 | }());
2145 |
2146 | // for CommonJS enviroments, export everything
2147 | if ( typeof exports !== "undefined" ) {
2148 | extend( exports, QUnit );
2149 | }
2150 |
2151 | // get at whatever the global object is, like window in browsers
2152 | }( (function() {return this;}.call()) ));
2153 |
--------------------------------------------------------------------------------