Created
October 7, 2018 16:15
-
-
Save younata/c2ca89f037eeade4d54e0c12c01221b7 to your computer and use it in GitHub Desktop.
Bad CSV Parser in swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Quick and dirty CSV parser I wrote. Handles edge cases badly. Doesn't perform well. Doesn't handle large csv files. | |
// But, hey, it solved my use case! | |
// Swift 4.2+ | |
func parseCSVBadly(csvData: Data) -> [[String]] { | |
guard let csv = String(data: csvData, encoding: .utf8) else { return [] } | |
return csv.components(separatedBy: CharacterSet.newlines).compactMap { line in | |
guard !line.hasPrefix("#") else { return nil } | |
return line.components(separatedBy: ",") | |
} | |
} | |
import Quick | |
import Nimble | |
final class CSVParserSpec: QuickSpec { | |
override func spec() { | |
it("Parses csvs") { | |
let data = "a,b,c,d\ne,f".data(using: .utf8)! | |
expect( | |
parseCSVBadly(csvData: data) | |
).to(equal([["a", "b", "c", "d"], ["e", "f"]])) | |
} | |
it("ignores lines prefixed with '#'s") { | |
let data = """ | |
a,b,c,d | |
# whatever. | |
e,f,g | |
""".data(using: .utf8)! | |
expect( | |
parseCSVBadly(csvData: data) | |
).to(equal([["a", "b", "c", "d"], ["e", "f", "g"]])) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment