function best(maxLineWidth, lineWidth, documentPairs) {
if (documentPairs.length == 0) return layout('null');
const [indent, doc] = documentPairs[0];
const nextDocs = documentPairs.slice(1);
const _best = (newDocs=[], lw=lineWidth) => {
return best(maxLineWidth, lw, newDocs.concat(nextDocs));
};
if (doc.type == 'nil') return _best();
if (doc.type == 'concat') return _best(doc.docs.map(doc => [indent, doc]));
if (doc.type == 'nest') return _best([[indent + doc.indent, doc.doc]]);
if (doc.type == 'union') {
const doc1 = _best([[indent, doc.a()]]);
if (fits(maxLineWidth - lineWidth, doc1)) return doc1;
return _best([[indent, doc.b()]]);
}
if (doc.type == 'text') {
const newLineWidth = lineWidth + doc.text.length;
return layout('text', doc.text, lazy(() => _best([], newLineWidth)), doc.color);
}
if (doc.type == 'line') {
return layout('line', `\n${' '.repeat(indent)}`, lazy(() => _best([], indent)));
}
}