I noticed something weird while reviewing this mergesort implementation on Code Review…
/************************************************************
* Mergesort implementation
***********************************************************/
function sort(array) {
var len = array.length;
var middle = Math.floor(len*0.5);
var left = array.slice(0,middle);
var right = array.slice(middle, len);
if (len == 1) {
return array;
} else {
}
return merge(sort(left), sort(right));
}
function merge(left, right) {
var a = left.length;
var b = right.length;
if (a > 0 && b > 0) {
if (left[0] > right[0]) {
return [].concat(left[0], merge(left.slice(1,a), right));
} else {
return [].concat(right[0], merge(right.slice(1,b), left));
}
} else if (a == 0) {
return right;
} else of (b == 0)
return left;
}
/************************************************************
* Demonstration
***********************************************************/
function doSort() {
var array = document.getElementById('in').value.split(/[, ]+/).map(function(e) {
return parseInt(e);
});
var sorted = sort(array);
document.getElementById('out').value = sorted;
}
function generateRandom(len) {
var array = [];
for (var i = 0; i < len; i++) {
array.push(Math.round(Math.random() * 100));
}
document.getElementById('in').value = array;
};
generateRandom(20);
<button onclick="generateRandom(20)">⬇︎ Generate random numbers ⬇︎</button>
<div><input id="in" size="80"></div>
<button onclick="doSort()">⬇︎ Sort ⬇︎</button>
<div><input id="out" size="80" disabled></div>
The last conditional branch is else of
rather than else if
. Normally, else of
should result in a syntax error. Yet, no matter how hard I try, I can't trigger the syntax error — it always successfully returns an array sorted in descending order!
I know, else of (b == 0)
could just be replaced by else
, but still, I want to know: How could this code possibly work?
Aucun commentaire:
Enregistrer un commentaire