|
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
|
2 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
3 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
5 |
|
6 /* |
|
7 * Date: 07 February 2001 |
|
8 * |
|
9 * Functionality common to Array testing - |
|
10 */ |
|
11 //----------------------------------------------------------------------------- |
|
12 |
|
13 |
|
14 var CHAR_LBRACKET = '['; |
|
15 var CHAR_RBRACKET = ']'; |
|
16 var CHAR_QT_DBL = '"'; |
|
17 var CHAR_QT = "'"; |
|
18 var CHAR_NL = '\n'; |
|
19 var CHAR_COMMA = ','; |
|
20 var CHAR_SPACE = ' '; |
|
21 var TYPE_STRING = typeof 'abc'; |
|
22 |
|
23 |
|
24 /* |
|
25 * If available, arr.toSource() gives more detail than arr.toString() |
|
26 * |
|
27 * var arr = Array(1,2,'3'); |
|
28 * |
|
29 * arr.toSource() |
|
30 * [1, 2, "3"] |
|
31 * |
|
32 * arr.toString() |
|
33 * 1,2,3 |
|
34 * |
|
35 * But toSource() doesn't exist in Rhino, so use our own imitation, below - |
|
36 * |
|
37 */ |
|
38 function formatArray(arr) |
|
39 { |
|
40 try |
|
41 { |
|
42 return arr.toSource(); |
|
43 } |
|
44 catch(e) |
|
45 { |
|
46 return toSource(arr); |
|
47 } |
|
48 } |
|
49 |
|
50 |
|
51 |
|
52 /* |
|
53 * Imitate SpiderMonkey's arr.toSource() method: |
|
54 * |
|
55 * a) Double-quote each array element that is of string type |
|
56 * b) Represent |undefined| and |null| by empty strings |
|
57 * c) Delimit elements by a comma + single space |
|
58 * d) Do not add delimiter at the end UNLESS the last element is |undefined| |
|
59 * e) Add square brackets to the beginning and end of the string |
|
60 */ |
|
61 function toSource(arr) |
|
62 { |
|
63 var delim = CHAR_COMMA + CHAR_SPACE; |
|
64 var elt = ''; |
|
65 var ret = ''; |
|
66 var len = arr.length; |
|
67 |
|
68 for (i=0; i<len; i++) |
|
69 { |
|
70 elt = arr[i]; |
|
71 |
|
72 switch(true) |
|
73 { |
|
74 case (typeof elt === TYPE_STRING) : |
|
75 ret += doubleQuote(elt); |
|
76 break; |
|
77 |
|
78 case (elt === undefined || elt === null) : |
|
79 break; // add nothing but the delimiter, below - |
|
80 |
|
81 default: |
|
82 ret += elt.toString(); |
|
83 } |
|
84 |
|
85 if ((i < len-1) || (elt === undefined)) |
|
86 ret += delim; |
|
87 } |
|
88 |
|
89 return CHAR_LBRACKET + ret + CHAR_RBRACKET; |
|
90 } |
|
91 |
|
92 |
|
93 function doubleQuote(text) |
|
94 { |
|
95 return CHAR_QT_DBL + text + CHAR_QT_DBL; |
|
96 } |
|
97 |
|
98 |
|
99 function singleQuote(text) |
|
100 { |
|
101 return CHAR_QT + text + CHAR_QT; |
|
102 } |
|
103 |