muxText
Take two strings with numbers in them and make a new string with numbers whose values are between the numbers in the other two strings.
by Kyle Falconer
HTML
<div id="out">
</div>
JavaScript
function mux(text1, text2) {
var t1_matches = text1.match(/\d+/g);
var t2_matches = text2.match(/\d+/g);
var val1, val2, middle_val;
var middle_text = text1;
for (var i = 0; i < Math.min(t1_matches.length, t2_matches.length); i++) {
val1 = parseInt(t1_matches[i], 10);
val2 = parseInt(t2_matches[i], 10);
middle_val = Math.abs(val1 - val2) / 2 + Math.min(val1, val2);
middle_text = middle_text.replace(val1, middle_val);
}
return middle_text;
}
(function() {
var $out = $('#out');
var tests = [
['0', '20', '10'],
['70%', '90%', '80%'],
['70% apples, 30% oranges', '90% apples, 10% oranges', '80% apples, 20% oranges'],
['10 apples, for Billy', '20 apples, for Billy2', '15 apples, for Billy'],
];
for (var i = 0; i < tests.length; i++) {
var result = mux(tests[i][0], tests[i][1]);
var pass = result === tests[i][2];
if (pass) {
$out.append("pass</br>")
} else {
$out.append("fail - expected '" + tests[i][1] + "' and got '" + result + "'</br>")
}
}
})();