collection.columnWidths

๐Ÿ’พ ็จ‹ๅผ๏ผš replit โฌ†๏ธ ้œ€่ฆ๏ผš .allElementsSameLength

// โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
// โ”‚    Collection + .columnWidths    โ”‚
// โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

extension Collection where 
    Element: Collection,            // each element is Collection, e.g. Array.
    Element.Index == Int,           // each element is Int indexed (column index).
    Element.Element: Collection     // each cell is Collection (has `count`), e.g. String.
{
    /// determine the max length (count) in every column of a 2D array of data.
    ///
    /// ### Explanation:
    /// ```
    ///   typealias Data  = [[String]]   // Data is Array, which is Collection.
    ///   typealias Row   = [String]     // Row == Data.Element, Array (Int indexed).
    ///   typealias Value = String       // Value == Row.Element, String, which is Collection too
    /// ```
    /// ### Example:
    /// - `[["a", "bc", "def"], ["ab", "cde", "f"]].columnWidths == Optional([2, 3, 3])`
    /// - `[["a", "b", "c"], ["a"]].columnWidths == nil`
    public var columnWidths: [Int]? {
        
        guard 
            allElementsSameLength,       // all rows same length
            let firstRow = first,        // data must at least have one row
            !firstRow.isEmpty            // row must at least have one cell
        else {
            return nil
        }
        
        // for each column (at index j), find that column's max string length.
        // every column contains at least one string, so max length (max()) can't be nil.
        return (0 ..< firstRow.count).map { j in 
            self                                // collection of elements (rows)
                .map { row in row[j].count }    // array of j-th elements' lengths
                .max()!                         // โญ force unwrap (max string length)
        }
    }
}

Last updated