Permalink
Browse files

Allow users to set the maximum length of array that the pretty-printer

will print out.

Currently, jasmine's pretty printer will iterate over an entire array,
formatting every element recursively. For very large arrays, this can
crash the page, or cause a 'slow script' warning.

This commit exposes a 'MAX_PRETTY_PRINT_ARRAY_LENGTH' option. If an
array larger than this is encountered, recursion will stop and the
array length will be printed instead e.g. "Array[20000000]".

The 'MAX_PRETTY_PRINT_ARRAY_LENGTH' option defaults to 100. This is
length of array will not kill your browser, but will allow you
to see big arrays, if you can stomach the output.
  • Loading branch information...
1 parent 367d3dc commit 33e4f5efbedd359dd8a04ed44d30fad838082d12 @mikemoraned mikemoraned committed with Greg Cobb and Luan Santos Jan 24, 2013
Showing with 24 additions and 4 deletions.
  1. +6 −2 lib/jasmine-core/jasmine.js
  2. +12 −0 spec/core/PrettyPrintSpec.js
  3. +5 −2 src/core/PrettyPrinter.js
  4. +1 −0 src/core/base.js
@@ -101,6 +101,7 @@ getJasmineRequireObj().base = (function (jasmineGlobal) {
};
j$.MAX_PRETTY_PRINT_DEPTH = 40;
+ j$.MAX_PRETTY_PRINT_ARRAY_LENGTH = 100;
j$.DEFAULT_TIMEOUT_INTERVAL = 5000;
j$.getGlobal = function() {
@@ -1497,14 +1498,17 @@ getJasmineRequireObj().pp = function(j$) {
this.append('Array');
return;
}
-
+ var length = Math.min(array.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH);
this.append('[ ');
- for (var i = 0; i < array.length; i++) {
+ for (var i = 0; i < length; i++) {
if (i > 0) {
this.append(', ');
}
this.format(array[i]);
}
+ if(array.length > length){
+ this.append(', ...');
+ }
this.append(' ]');
};
@@ -70,6 +70,18 @@ describe("j$.pp", function () {
expect(j$.pp(frozenObject)).toEqual("{ foo: { bar: 'baz' }, circular: <circular reference: Object> }");
});
+ it("should truncate arrays that are longer than j$.MAX_PRETTY_PRINT_ARRAY_LENGTH", function() {
+ var originalMaxLength = j$.MAX_PRETTY_PRINT_ARRAY_LENGTH;
+ var array = [1, 2, 3];
+
+ try {
+ j$.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2;
+ expect(j$.pp(array)).toEqual("[ 1, 2, ... ]");
+ } finally {
+ j$.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxLength;
+ }
+ });
+
it("should stringify RegExp objects properly", function() {
expect(j$.pp(/x|y|z/)).toEqual("/x|y|z/");
});
@@ -82,14 +82,17 @@ getJasmineRequireObj().pp = function(j$) {
this.append('Array');
return;
}
-
+ var length = Math.min(array.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH);
this.append('[ ');
- for (var i = 0; i < array.length; i++) {
+ for (var i = 0; i < length; i++) {
if (i > 0) {
this.append(', ');
}
this.format(array[i]);
}
+ if(array.length > length){
+ this.append(', ...');
+ }
this.append(' ]');
};
View
@@ -9,6 +9,7 @@ getJasmineRequireObj().base = (function (jasmineGlobal) {
};
j$.MAX_PRETTY_PRINT_DEPTH = 40;
+ j$.MAX_PRETTY_PRINT_ARRAY_LENGTH = 100;
j$.DEFAULT_TIMEOUT_INTERVAL = 5000;
j$.getGlobal = function() {

0 comments on commit 33e4f5e

Please sign in to comment.