mirror of
https://github.com/rjNemo/underscore
synced 2026-06-10 20:46:42 +00:00
docs: add examples
This commit is contained in:
parent
b64bbb9fea
commit
df84e6f05d
2 changed files with 50 additions and 0 deletions
28
README.md
28
README.md
|
|
@ -9,6 +9,34 @@
|
||||||
|
|
||||||
It is mostly a port from the `underscore.js` library based on generics brought by `go1.18`.
|
It is mostly a port from the `underscore.js` library based on generics brought by `go1.18`.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
Please check out the [examples](examples) to see how to use the library.
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
u "github.com/rjNemo/underscore"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
|
||||||
|
// filter even numbers from the slice
|
||||||
|
isEven := func(n int) bool { return n%2 == 0 }
|
||||||
|
evens := u.Filter(numbers, isEven)
|
||||||
|
// square every number in the slice
|
||||||
|
toSquare := func(n int) int { return n * n }
|
||||||
|
squares := u.Map(evens, toSquare)
|
||||||
|
// reduce to the sum
|
||||||
|
sum := func(n, acc int) int { return n + acc }
|
||||||
|
res := u.Reduce(squares, sum, 0)
|
||||||
|
|
||||||
|
fmt.Println(res) // 110
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
|
|
||||||
These instructions will get you a copy of the project up and running on your local machine for development and testing
|
These instructions will get you a copy of the project up and running on your local machine for development and testing
|
||||||
|
|
|
||||||
22
examples/filterMapReduce.go
Normal file
22
examples/filterMapReduce.go
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
u "github.com/rjNemo/underscore"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
|
||||||
|
// filter even numbers from the slice
|
||||||
|
isEven := func(n int) bool { return n%2 == 0 }
|
||||||
|
evens := u.Filter(numbers, isEven)
|
||||||
|
// square every numbers numbers in the slice
|
||||||
|
toSquare := func(n int) int { return n * n }
|
||||||
|
squares := u.Map(evens, toSquare)
|
||||||
|
// reduce to the sum
|
||||||
|
sum := func(n, acc int) int { return n + acc }
|
||||||
|
res := u.Reduce(squares, sum, 0)
|
||||||
|
|
||||||
|
fmt.Println(res)
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue