Skip to content

Commit 5039539

Browse files
committed
Collection and files functions
1 parent 463c8e6 commit 5039539

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

xcollection/xcollection.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package xcollection
2+
3+
// StringBoolMapKeys - extract map keys as slice
4+
func StringBoolMapKeys(m map[string]bool) []string {
5+
keys := make([]string, 0, len(m))
6+
for kk := range m {
7+
keys = append(keys, kk)
8+
}
9+
return keys
10+
}

xcollection/xcollection_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package xcollection
2+
3+
import (
4+
"github.com/stretchr/testify/assert"
5+
"testing"
6+
)
7+
8+
func TestStringExtractions(t *testing.T) {
9+
10+
keys := StringBoolMapKeys(map[string]bool{
11+
"qwe": true,
12+
"123": true,
13+
})
14+
15+
assert.Equal(t, 2, len(keys))
16+
}

xfiles/xfiles.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package xfiles
2+
3+
import (
4+
"bufio"
5+
"github.com/unidev-platform/golang-core/xcollection"
6+
"os"
7+
"strings"
8+
)
9+
10+
// ReadDistinctFileLines - Read text file lines as slice without empty and duplicates
11+
func ReadDistinctFileLines(path string)([]string, error) {
12+
var linesMap map[string]bool
13+
14+
file, err := os.Open(path)
15+
if err != nil {
16+
return nil, err
17+
}
18+
defer file.Close()
19+
20+
scanner := bufio.NewScanner(file)
21+
for scanner.Scan() {
22+
line := strings.TrimSpace(scanner.Text())
23+
if len(line) > 0 {
24+
linesMap[line] = true
25+
}
26+
}
27+
28+
return xcollection.StringBoolMapKeys(linesMap), scanner.Err()
29+
30+
}

0 commit comments

Comments
 (0)