From 929c5b58a08473cb98d5aadc196525838f71187c Mon Sep 17 00:00:00 2001 From: Karma Riuk Date: Sat, 5 Aug 2023 10:48:41 +0200 Subject: [PATCH] Reader -> Reader+Parser refactoring: moved the reading of the lines to its own function --- io/reader/text.go | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/io/reader/text.go b/io/reader/text.go index 24b28bb..4c54d8b 100644 --- a/io/reader/text.go +++ b/io/reader/text.go @@ -12,27 +12,37 @@ type TextReader struct { } func (r TextReader) Read() (*maze.RawMaze, error) { - var lines []string - - if _, err := os.Stat(r.Filename); err != nil { - return nil, err - } - - file, err := os.Open(r.Filename) + lines, err := getLines(r.Filename) if err != nil { return nil, err } - { - scanner := bufio.NewScanner(file) - scanner.Split(bufio.ScanLines) + return &maze.RawMaze{ + PathChar: r.PathChar, + WallChar: r.WallChar, + Data: *lines, + }, nil +} - for scanner.Scan() { - line := scanner.Text() - lines = append(lines, line) - } - file.Close() +func getLines(filename string) (*[]string, error) { + var lines []string + if _, err := os.Stat(filename); err != nil { + return nil, err } - return &maze.RawMaze{PathChar: r.PathChar, WallChar: r.WallChar, Data: lines}, nil + file, err := os.Open(filename) + if err != nil { + return nil, err + } + defer file.Close() + + scanner := bufio.NewScanner(file) + scanner.Split(bufio.ScanLines) + + for scanner.Scan() { + line := scanner.Text() + lines = append(lines, line) + } + + return &lines, nil }