Bug 664528 - [].sort misbehaves when the array being sorted starts with at least one hole and otherwise contains only holes and |undefined| as its elements. r=jandem
authorJeff Walden <jwalden@mit.edu>
Wed, 13 Feb 2013 15:47:25 -0800
changeset 122202 a1310b986ebe61e0e8eeb618bb1d0aba89f4b658
parent 122201 fa40088b0833af00e3d3b064cddf7c2eba0114c2
child 122203 eb1a14e09f50df22978eea54caf2bf9887821e7a
push id1
push userroot
push dateMon, 20 Oct 2014 17:29:22 +0000
reviewersjandem
bugs664528
milestone21.0a1
Bug 664528 - [].sort misbehaves when the array being sorted starts with at least one hole and otherwise contains only holes and |undefined| as its elements. r=jandem
js/src/jsarray.cpp
js/src/tests/ecma_5/Array/sort-array-with-holes-and-undefined.js
--- a/js/src/jsarray.cpp
+++ b/js/src/jsarray.cpp
@@ -1577,20 +1577,25 @@ js::array_sort(JSContext *cx, unsigned a
                 ++undefs;
                 continue;
             }
             vec.infallibleAppend(v);
             allStrings = allStrings && v.isString();
             allInts = allInts && v.isInt32();
         }
 
+
+        /*
+         * If the array only contains holes, we're done.  But if it contains
+         * undefs, those must be sorted to the front of the array.
+         */
         n = vec.length();
-        if (n == 0) {
+        if (n == 0 && undefs == 0) {
             args.rval().setObject(*obj);
-            return true; /* The array has only holes and undefs. */
+            return true;
         }
 
         /* Here len == n + undefs + number_of_holes. */
         if (fval.isNull()) {
             /*
              * Sort using the default comparator converting all elements to
              * strings.
              */
new file mode 100644
--- /dev/null
+++ b/js/src/tests/ecma_5/Array/sort-array-with-holes-and-undefined.js
@@ -0,0 +1,32 @@
+/*
+ * Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/licenses/publicdomain/
+ */
+
+//-----------------------------------------------------------------------------
+var BUGNUMBER = 664528;
+var summary =
+  "Sorting an array containing only holes and |undefined| should move all " +
+  "|undefined| to the start of the array";
+
+print(BUGNUMBER + ": " + summary);
+
+/**************
+ * BEGIN TEST *
+ **************/
+
+var a = [, , , undefined];
+a.sort();
+
+assertEq(a.hasOwnProperty(0), true);
+assertEq(a[0], undefined);
+assertEq(a.hasOwnProperty(1), false);
+assertEq(a.hasOwnProperty(2), false);
+assertEq(a.hasOwnProperty(3), false);
+
+/******************************************************************************/
+
+if (typeof reportCompare === "function")
+  reportCompare(true, true);
+
+print("Tests complete");