//
// 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: "
")
return " | "
}
func html() -> String {
let all = self.colums().joined(separator: "")
return " | | \(all) |
"
}
}
extension Array where Element : HTMLRepresentable {
func writeHTML(fileName: String, limit: Int? = 10) {
var html = "\n"
html.append("")
html.append(Element.htmlHeaders())
html.append("\n")
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
")
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
}