From 5daab60e5e79b5efc76ca8cb53d4525c949c1568 Mon Sep 17 00:00:00 2001 From: Ben Burwell Date: Wed, 18 Nov 2015 16:23:46 -0500 Subject: Deduplicate string -> float64 conversion Created a function to convert lat & long from strings to floats. Handling an improperly formatted file will not be supported; if this occurs, the lat & long returned from the API will just be (0,0). --- database.go | 32 +++++++++++--------------------- 1 file changed, 11 insertions(+), 21 deletions(-) diff --git a/database.go b/database.go index 8dbf942..964915c 100644 --- a/database.go +++ b/database.go @@ -37,15 +37,9 @@ func (db *ZipcodeDatabase) LoadFromCSV(filename string) error { if err != nil { return err } - for _, row := range zips { - details, err := getDetailsFromRow(row) - if err != nil { - return err - } - db.Insert(row[0], details) + db.Insert(row[0], getDetailsFromRow(row)) } - return nil } @@ -55,32 +49,28 @@ func getZipsFromFile(filename string) ([][]string, error) { return nil, err } defer reader.Close() - csvReader := csv.NewReader(reader) zips, err := csvReader.ReadAll() if err != nil { return nil, err } - return zips, nil } -func getDetailsFromRow(row []string) (*ZipcodeDetails, error) { - lat, err := strconv.ParseFloat(strings.TrimSpace(row[2]), 64) - if err != nil { - return nil, err - } - lon, err := strconv.ParseFloat(strings.TrimSpace(row[3]), 64) +func getFloat(stringVal string) float64 { + floatVal, err := strconv.ParseFloat(strings.TrimSpace(stringVal), 64) if err != nil { - return nil, err + return 0 + } else { + return floatVal } +} - zip := &ZipcodeDetails{ +func getDetailsFromRow(row []string) *ZipcodeDetails { + return &ZipcodeDetails{ State: row[1], - Latitude: lat, - Longitude: lon, + Latitude: getFloat(row[2]), + Longitude: getFloat(row[3]), City: row[4], } - - return zip, nil } -- cgit v1.2.3