ASCII table where field can have newlines

后端 未结 3 953
花落未央
花落未央 2021-01-07 10:50

I have following function that display ASCII table

        function ascii_table(array, header) {
            if (!array.length) {
                return \'\'         


        
3条回答
  •  北荒
    北荒 (楼主)
    2021-01-07 11:44

    This can be done without any modification of your code by expanding your array -- adding one new row for each extra line of the comment. The first row would be the same as before -- except that the comment cell contains only the first line of the comment. Every additional line would contain empty cells -- except the comment cell, which would contain that comment line.

    I'd break out most of the functions for readability, but to keep with your coding style, it might look like this:

      array = array.reduce(function (carry, originalRow) {
        var commentLines = originalRow[4].split(/\n/g);
    
        var rows = commentLines.map(function (commentLine, rowIndex) {
            var newRow = originalRow.map(function (originalCellContent, columnIndex) {
                var cellContent = '';
    
                if (rowIndex === 0) {
                    cellContent = originalCellContent;
                }
                if (columnIndex === 4) {
                    cellContent = commentLine;
                }
    
                return cellContent;
            });
            carry.push(newRow);
        });
    
        return carry;
      }, []);
    

    A fork of your fiddle is here, with this code added.

提交回复
热议问题