Archive for July 8th, 2008

JavaScript reduce

Posted in programming on July 8th, 2008 by Christopher Owen – 2 Comments

Tonight Matt posted a JavaScript solution to a problem he saw described elsewhere. Here’s a version that I whipped up to use JavaScript 1.8′s new Array.prototype.reduce function.

var arrVal = ["a", "b", "c", "c", "d", "e", "e", "e", "e", "e",
  "f", "e", "f", "e", "f", "a", "a", "a", "f", "f", "f"];
 
function group(previousValue, currentValue, index, arr)
{
	if (index > 0  && arr[index - 1] == currentValue)
		return previousValue.slice(0,-1).concat([previousValue.slice(-1)[0].concat(currentValue)]);
	return previousValue.concat([[currentValue]]);
}
 
function format(previousValue, currentValue, index, arr)
{
	return previousValue.concat(
		currentValue.length < 3 ? 
		currentValue.join(" ") :
		currentValue.slice(0,2).join(" ") + 
			" <span>" + currentValue.slice(2).join(" ") + "<span>");
}
 
print(arrVal.reduce(group, []).reduce(format, []).join(" "));