JavaScript median of three
Three ways to compute the median-of-three in JavaScript
by Ray Toal
HTML
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-git.css">
<script src="https://code.jquery.com/qunit/qunit-git.js"></script>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
JavaScript
/*
* An illustration of several ways to implement the median of three
* in JavaScript.
*/
let medians = [
/*
* Returns the median of its three arguments, INTERPRETED AS STRINGS.
*/
function (a, b, c) {
return [a, b, c].sort()[1];
},
/*
* Returns the median of its three arguments, using as an ordering
* whatever "<" means for its arguments.
*/
function (a, b, c) {
// Code is probably too compact for most readers.
return a<b? b<c? b : a<c? c : a : b<c? a<c? a : c : b;
},
/*
* Returns the median of its three arguments, using as an ordering
* whatever "<" means for its arguments.
*/
function (a, b, c) {
// Code is long as stringy; probably not the most readable.
if (a < b) {
if (b < c) {
return b;
} else if (a < c) {
return c;
} else {
return a;
}
} else {
if (b < c) {
if (a < c) {
return a;
} else {
return c;
}
} else {
return b;
}
}
}
];
QUnit.test("String-based median", t => {
let median = medians[0];
t.equal(median(1, 4, 10), 10);
t.equal(median(1, 10, 4), 10);
t.equal(median(4, 1, 10), 10);
t.equal(median(4, 10, 1), 10);
t.equal(median(10, 1, 4), 10);
t.equal(median(10, 4, 1), 10);
});
QUnit.test("Compact median", t => {
let median = medians[1];
t.equal(median(1, 4, 10), 4);
t.equal(median(1, 10, 4), 4);
t.equal(median(4, 1, 10), 4);
t.equal(median(4, 10, 1), 4);
t.equal(median(10, 1, 4), 4);
t.equal(median(10, 4, 1), 4);
});
QUnit.test("Stringy median", t => {
let median = medians[2];
t.equal(median(1, 4, 10), 4);
t.equal(median(1, 10, 4), 4);
t.equal(median(4, 1, 10), 4);
t.equal(median(4, 10, 1), 4);
t.equal(median(10, 1, 4), 4);
t.equal(median(10, 4, 1), 4);
});