From bc623da74b213d65dff424d347bd32695430c309 Mon Sep 17 00:00:00 2001 From: Chris Lane Date: Sat, 15 Feb 2020 15:56:25 -0500 Subject: [PATCH] feat: issue #260 Dramatically improves the usefulness of `--search` by outputting "chunked" results. This removes the need (usually) to search and then manually open a cheatsheet. --- internal/sheet/search.go | 15 +++++---------- internal/sheet/search_test.go | 8 ++++---- 2 files changed, 9 insertions(+), 14 deletions(-) diff --git a/internal/sheet/search.go b/internal/sheet/search.go index ed9f9fd..5e8d207 100644 --- a/internal/sheet/search.go +++ b/internal/sheet/search.go @@ -9,21 +9,16 @@ import ( func (s *Sheet) Search(reg *regexp.Regexp) string { // record matches - matches := []string{} + matches := "" // search through the cheatsheet's text line by line - // TODO: searching line-by-line is surely the "naive" approach. Revisit this - // later with an eye for performance improvements. - for _, line := range strings.Split(s.Text, "\n") { + for _, line := range strings.Split(s.Text, "\n\n") { // exit early if the line doesn't match the regex - if !reg.MatchString(line) { - continue + if reg.MatchString(line) { + matches += line + "\n\n" } - - // record the match - matches = append(matches, line) } - return strings.Join(matches, "\n") + return strings.TrimSpace(matches) } diff --git a/internal/sheet/search_test.go b/internal/sheet/search_test.go index 41dc41c..d6013c2 100644 --- a/internal/sheet/search_test.go +++ b/internal/sheet/search_test.go @@ -36,7 +36,7 @@ func TestSearchSingleMatch(t *testing.T) { // mock a cheatsheet sheet := Sheet{ - Text: "The quick brown fox\njumped over\nthe lazy dog.", + Text: "The quick brown fox\njumped over\n\nthe lazy dog.", } // compile the search regex @@ -49,7 +49,7 @@ func TestSearchSingleMatch(t *testing.T) { matches := sheet.Search(reg) // specify the expected results - want := "The quick brown fox" + want := "The quick brown fox\njumped over" // assert that the correct matches were returned if matches != want { @@ -67,7 +67,7 @@ func TestSearchMultiMatch(t *testing.T) { // mock a cheatsheet sheet := Sheet{ - Text: "The quick brown fox\njumped over\nthe lazy dog.", + Text: "The quick brown fox\n\njumped over\n\nthe lazy dog.", } // compile the search regex @@ -80,7 +80,7 @@ func TestSearchMultiMatch(t *testing.T) { matches := sheet.Search(reg) // specify the expected results - want := "The quick brown fox\nthe lazy dog." + want := "The quick brown fox\n\nthe lazy dog." // assert that the correct matches were returned if !reflect.DeepEqual(matches, want) {