// Pick a random ngram weighted by frequency.
function(head, req) {
	provides("json", function () {
		var allowEmpty = !("nonempty" in req.query);
		var total = 0;
		var rows = [];
		var row;
		while (row = getRow()) {
			if (allowEmpty || row.key.some(Boolean)) {
				rows.push(row);
				total += row.value;
				row.cumulative = total;
			}
		}
		var chosenIndex = Math.random() * total;
		var chosenNgram = null;
		for (var i = 0; i < rows.length; i++) {
			var row = rows[i];
			if (row.cumulative > chosenIndex) {
				chosenNgram = row.key;
				break;
			}
		}
		return JSON.stringify(chosenNgram);
	});
}

@@ -140,16 +140,290 @@
 query);%0A
+%0A%09%09// Two modes. If chosenIndex is null, read all rows and pick a random%0A%09%09// one. If chosenIndex is a number, read up to the row with that%0A%09%09// cumulative value, and return it.%0A%09%09var chosenNgram = null;%0A%09%09var chosenIndex = req.query.i;%0A%09%09var random = chosenIndex == null;%0A%0A
 %09%09var to
@@ -536,28 +536,8 @@
 ) %7B%0A
-%09%09%09%09rows.push(row);%0A
 %09%09%09%09
@@ -556,16 +556,35 @@
 .value;%0A
+%09%09%09%09if (random) %7B%0A%09
 %09%09%09%09row.
@@ -610,80 +610,185 @@
 %0A%09%09%09
-%7D%0A%09%09%7D%0A%09%09var chosenIndex = Math.random() * total;%0A%09%09var chosenNgram = nul
+%09%09rows.push(row);%0A%09%09%09%09%7D else if (total %3E chosenIndex) %7B%0A%09%09%09%09%09chosenNgram = row.key;%0A%09%09%09%09%09return JSON.stringify(chosenNgram);%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%7D%0A%0A%09%09chosenIndex = Math.random() * tota
 l;%0A%09

Allow picking ngrams (list) by cumulative index