Skip to content

Commit 8dd9aee

Browse files
committed
copy the input in the length < 2 case also
and throw an Error if input is not an array.
1 parent d1caf49 commit 8dd9aee

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

solutions/javascript/quick-sort.js

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,14 @@ module.exports = function quickSort(input, compare) {
55
greater = [],
66
pivot;
77

8-
// Not an array, empty or array of 1 is already sorted
9-
if (!Array.isArray(input) || input.length < 2) {
10-
return input;
8+
if (!Array.isArray(input)) {
9+
throw new Error('Can only sort arrays.');
10+
}
11+
12+
var array = input.slice(0); // make a copy of the array
13+
14+
if (array.length < 2) {
15+
return array;
1116
}
1217

1318
// Create a compare func if not passed in
@@ -17,8 +22,6 @@ module.exports = function quickSort(input, compare) {
1722
};
1823
}
1924

20-
var array = input.slice(0); // make a copy of the array
21-
2225
// Get our pivot, this can be random
2326
pivot = array.splice(~~(Math.random() * array.length), 1);
2427

tests/javascript/quick-sort.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,17 @@ var quickSort = require('../../solutions/javascript/quick-sort');
55

66
describe('Quick Sort', function(){
77

8+
it('throws error if input not an array', function() {
9+
10+
try {
11+
quickSort(null);
12+
} catch (err) {
13+
return;
14+
}
15+
16+
assert(false, 'Expected exception to be thrown.');
17+
});
18+
819
it('handles empty list', function() {
920
var results = quickSort([]);
1021
assert(Array.isArray(results), 'Expected result to be array');

0 commit comments

Comments
 (0)