An amazing project that generates micro reports from tournament results
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
pa-tournament-stats/TournamentStats/utils/ColumnRepresentable.swift

93 lines
2.2 KiB

//
// CSVUtils.swift
// TournamentStats
//
// Created by Laurent Morvillier on 03/06/2019.
// Copyright © 2019 Stax River. All rights reserved.
//
import Foundation
public protocol ColumnRepresentable {
static func headers() -> [String]
func colums() -> [String]
}
public protocol HTMLRepresentable : ColumnRepresentable {
static func htmlHeaders() -> String
func html() -> String
}
extension HTMLRepresentable {
static func htmlHeaders() -> String {
let all = self.headers().joined(separator: "</td><td>")
return "<tr class=\"table-header\"><td>\(all)</td></tr>"
}
func html() -> String {
let all = self.colums().joined(separator: "</td><td>")
return "<tr><td>\(all)</td></tr>"
}
}
extension Array where Element : HTMLRepresentable {
func writeHTML(fileName: String, limit: Int? = 10) {
var html = "<table class=\"wp-block-table alignwide\">\n"
html.append("<thead>")
html.append(Element.htmlHeaders())
html.append("</thead>\n<tbody>")
let max = limit ?? Int.max
for (index, rep) in self.enumerated() {
html.append("\n")
html.append(rep.html())
if index + 1 >= max {
break
}
}
html.append("\n</tbody></table>")
do {
try FileWriter.writeToDocumentDirectory(content: html, fileName: fileName)
} catch {
print(error)
}
}
}
extension Array where Element : CSVRepresentable {
func writeCSV(file: String, limit: Int? = 10) {
var string = Element.csvHeaders()
let max = limit ?? Int.max
for (index, rep) in self.enumerated() {
string.append("/n")
string.append(rep.csv())
if index >= max {
break
}
}
do {
try FileWriter.writeToDocumentDirectory(content: string, fileName: file)
} catch {
print(error)
}
}
}
public protocol CSVRepresentable {
static func csvHeaders() -> String
func csv() -> String
}