github.com/l3x/learn-fp-go@v0.0.0-20171228022418-7639825d0b71/1-functional-fundamentals/ch03-hof/03_hof/src/hof/utils.go (about)

     1  package hof
     2  
     3  import (
     4  	"path/filepath"
     5  	"encoding/csv"
     6  	"os"
     7  	"log"
     8  	"fmt"
     9  	s "strings"
    10  )
    11  
    12  const DASHES = "-----------------------"
    13  
    14  func PrintCars(title string, cars Collection) {
    15  	log.Printf("\n%s\n%s\n", title, DASHES)
    16  	for _, car := range cars {
    17  		log.Printf("car: %v\n", car)
    18  	}
    19  }
    20  
    21  func PrintCars2(title string, cars CarCollection) {
    22  	log.Printf("\n%s\n%s\n", title, DASHES)
    23  	for _, car := range cars {
    24  		log.Printf("car: %v\n", car)
    25  	}
    26  }
    27  
    28  func CsvToStruct(fileName string) Collection {
    29  	pwd, err := filepath.Abs(filepath.Dir(os.Args[0]))
    30  	//pwd = "./1-functional-fundamentals/ch03-hof/hof"
    31  	if err != nil {
    32  		log.Fatal(err)
    33  		os.Exit(1)
    34  	}
    35  	csvfile, err := os.Open(fmt.Sprintf("%s/%s", pwd, fileName))
    36  	if err != nil {
    37  		log.Fatal(err)
    38  		os.Exit(1)
    39  	}
    40  	defer csvfile.Close()
    41  	reader := csv.NewReader(csvfile)
    42  	reader.FieldsPerRecord = -1
    43  	rawCSVdata, err := reader.ReadAll()
    44  	if err != nil {
    45  		log.Println(err)
    46  		os.Exit(1)
    47  	}
    48  	var cars Collection
    49  	for _, car := range rawCSVdata {
    50  		cars = append(cars, car[0])
    51  	}
    52  	return cars
    53  }
    54  
    55  func GetMake(sentence string) string {
    56  	ret := sentence
    57  	posSpace := s.Index(sentence, " ")
    58  	if posSpace >= 0 {
    59  		ret = sentence[:(posSpace)]
    60  	}
    61  	return ret
    62  }
    63  
    64  func GetModel(sentence string) string {
    65  	ret := sentence
    66  	posSpace := s.Index(sentence, " ")
    67  	if posSpace >= 0 {
    68  		ret = sentence[posSpace:]
    69  	}
    70  	return ret
    71  }