pax_global_header 0000666 0000000 0000000 00000000064 14570052437 0014521 g ustar 00root root 0000000 0000000 52 comment=307d0db21292676ac9d469826525c3630f47f63a
objx-0.5.2/ 0000775 0000000 0000000 00000000000 14570052437 0012467 5 ustar 00root root 0000000 0000000 objx-0.5.2/.codeclimate.yml 0000664 0000000 0000000 00000000443 14570052437 0015542 0 ustar 00root root 0000000 0000000 engines:
gofmt:
enabled: true
golint:
enabled: true
govet:
enabled: true
exclude_patterns:
- ".github/"
- "vendor/"
- "codegen/"
- "*.yml"
- ".*.yml"
- "*.md"
- "Gopkg.*"
- "doc.go"
- "type_specific_codegen_test.go"
- "type_specific_codegen.go"
- ".gitignore"
- "LICENSE"
objx-0.5.2/.github/ 0000775 0000000 0000000 00000000000 14570052437 0014027 5 ustar 00root root 0000000 0000000 objx-0.5.2/.github/CODE_OF_CONDUCT.md 0000664 0000000 0000000 00000006217 14570052437 0016634 0 ustar 00root root 0000000 0000000 # Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at hanzei@mailbox.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
objx-0.5.2/.github/PULL_REQUEST_TEMPLATE.md 0000664 0000000 0000000 00000000542 14570052437 0017631 0 ustar 00root root 0000000 0000000
#### Summary
#### Checklist
[Place an '[x]' (no spaces) in all applicable fields. Please remove unrelated fields.]
- [ ] Tests are passing: `task test`
- [ ] Code style is correct: `task lint`
objx-0.5.2/.github/dependabot.yml 0000664 0000000 0000000 00000000261 14570052437 0016656 0 ustar 00root root 0000000 0000000 version: 2
updates:
- package-ecosystem: gomod
directory: /
schedule:
interval: daily
- package-ecosystem: github-actions
directory: /
schedule:
interval: daily
objx-0.5.2/.github/workflows/ 0000775 0000000 0000000 00000000000 14570052437 0016064 5 ustar 00root root 0000000 0000000 objx-0.5.2/.github/workflows/go.yml 0000664 0000000 0000000 00000002357 14570052437 0017223 0 ustar 00root root 0000000 0000000 name: Go
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
env:
CC_TEST_REPORTER_ID: 68feaa3410049ce73e145287acbcdacc525087a30627f96f04e579e75bd71c00
runs-on: ubuntu-latest
strategy:
matrix:
go: [ '1.22', '1.21', '1.20' ]
steps:
- uses: actions/checkout@v4
- name: Pre-run
run: |
curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
chmod +x ./cc-test-reporter
./cc-test-reporter before-build
curl -sL https://taskfile.dev/install.sh | sh
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go }}
- name: Setup go module cache
uses: actions/cache@v4
with:
path: |
~/.cache/go-build
~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go-
- name: Lint
run: diff -u <(echo -n) <(./bin/task lint)
- name: Test
run: ./bin/task test-coverage
- name: Post run
run: ./cc-test-reporter after-build format-coverage -t gocov --prefix github.com/stretchr/objx .cover/c.out --exit-code $?
objx-0.5.2/.gitignore 0000664 0000000 0000000 00000000271 14570052437 0014457 0 ustar 00root root 0000000 0000000 # Binaries for programs and plugins
*.exe
*.dll
*.so
*.dylib
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
objx-0.5.2/LICENSE 0000664 0000000 0000000 00000002135 14570052437 0013475 0 ustar 00root root 0000000 0000000 The MIT License
Copyright (c) 2014 Stretchr, Inc.
Copyright (c) 2017-2018 objx contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
objx-0.5.2/README.md 0000664 0000000 0000000 00000006701 14570052437 0013752 0 ustar 00root root 0000000 0000000 # Objx
[](https://travis-ci.org/stretchr/objx)
[](https://goreportcard.com/report/github.com/stretchr/objx)
[](https://codeclimate.com/github/stretchr/objx/maintainability)
[](https://codeclimate.com/github/stretchr/objx/test_coverage)
[](https://sourcegraph.com/github.com/stretchr/objx)
[](https://pkg.go.dev/github.com/stretchr/objx)
Objx - Go package for dealing with maps, slices, JSON and other data.
Get started:
- Install Objx with [one line of code](#installation), or [update it with another](#staying-up-to-date)
- Check out the API Documentation http://pkg.go.dev/github.com/stretchr/objx
## Overview
Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes a powerful `Get` method (among others) that allows you to easily and quickly get access to data within the map, without having to worry too much about type assertions, missing data, default values etc.
### Pattern
Objx uses a predictable pattern to make access data from within `map[string]interface{}` easy. Call one of the `objx.` functions to create your `objx.Map` to get going:
m, err := objx.FromJSON(json)
NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, the rest will be optimistic and try to figure things out without panicking.
Use `Get` to access the value you're interested in. You can use dot and array
notation too:
m.Get("places[0].latlng")
Once you have sought the `Value` you're interested in, you can use the `Is*` methods to determine its type.
if m.Get("code").IsStr() { // Your code... }
Or you can just assume the type, and use one of the strong type methods to extract the real value:
m.Get("code").Int()
If there's no value there (or if it's the wrong type) then a default value will be returned, or you can be explicit about the default value.
Get("code").Int(-1)
If you're dealing with a slice of data as a value, Objx provides many useful methods for iterating, manipulating and selecting that data. You can find out more by exploring the index below.
### Reading data
A simple example of how to use Objx:
// Use MustFromJSON to make an objx.Map from some JSON
m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`)
// Get the details
name := m.Get("name").Str()
age := m.Get("age").Int()
// Get their nickname (or use their name if they don't have one)
nickname := m.Get("nickname").Str(name)
### Ranging
Since `objx.Map` is a `map[string]interface{}` you can treat it as such. For example, to `range` the data, do what you would expect:
m := objx.MustFromJSON(json)
for key, value := range m {
// Your code...
}
## Installation
To install Objx, use go get:
go get github.com/stretchr/objx
### Staying up to date
To update Objx to the latest version, run:
go get -u github.com/stretchr/objx
### Supported go versions
We currently support the three recent major Go versions.
## Contributing
Please feel free to submit issues, fork the repository and send pull requests!
objx-0.5.2/Taskfile.yml 0000664 0000000 0000000 00000000663 14570052437 0014761 0 ustar 00root root 0000000 0000000 version: '3'
tasks:
default:
deps: [test]
lint:
desc: Checks code style
cmds:
- gofmt -d -s *.go
- go vet ./...
silent: true
lint-fix:
desc: Fixes code style
cmds:
- gofmt -w -s *.go
test:
desc: Runs go tests
cmds:
- go test -race ./...
test-coverage:
desc: Runs go tests and calculates test coverage
cmds:
- go test -race -coverprofile=c.out ./...
objx-0.5.2/accessors.go 0000664 0000000 0000000 00000011264 14570052437 0015007 0 ustar 00root root 0000000 0000000 package objx
import (
"reflect"
"regexp"
"strconv"
"strings"
)
const (
// PathSeparator is the character used to separate the elements
// of the keypath.
//
// For example, `location.address.city`
PathSeparator string = "."
// arrayAccessRegexString is the regex used to extract the array number
// from the access path
arrayAccessRegexString = `^(.+)\[([0-9]+)\]$`
// mapAccessRegexString is the regex used to extract the map key
// from the access path
mapAccessRegexString = `^([^\[]*)\[([^\]]+)\](.*)$`
)
// arrayAccessRegex is the compiled arrayAccessRegexString
var arrayAccessRegex = regexp.MustCompile(arrayAccessRegexString)
// mapAccessRegex is the compiled mapAccessRegexString
var mapAccessRegex = regexp.MustCompile(mapAccessRegexString)
// Get gets the value using the specified selector and
// returns it inside a new Obj object.
//
// If it cannot find the value, Get will return a nil
// value inside an instance of Obj.
//
// Get can only operate directly on map[string]interface{} and []interface.
//
// # Example
//
// To access the title of the third chapter of the second book, do:
//
// o.Get("books[1].chapters[2].title")
func (m Map) Get(selector string) *Value {
rawObj := access(m, selector, nil, false)
return &Value{data: rawObj}
}
// Set sets the value using the specified selector and
// returns the object on which Set was called.
//
// Set can only operate directly on map[string]interface{} and []interface
//
// # Example
//
// To set the title of the third chapter of the second book, do:
//
// o.Set("books[1].chapters[2].title","Time to Go")
func (m Map) Set(selector string, value interface{}) Map {
access(m, selector, value, true)
return m
}
// getIndex returns the index, which is hold in s by two branches.
// It also returns s without the index part, e.g. name[1] will return (1, name).
// If no index is found, -1 is returned
func getIndex(s string) (int, string) {
arrayMatches := arrayAccessRegex.FindStringSubmatch(s)
if len(arrayMatches) > 0 {
// Get the key into the map
selector := arrayMatches[1]
// Get the index into the array at the key
// We know this can't fail because arrayMatches[2] is an int for sure
index, _ := strconv.Atoi(arrayMatches[2])
return index, selector
}
return -1, s
}
// getKey returns the key which is held in s by two brackets.
// It also returns the next selector.
func getKey(s string) (string, string) {
selSegs := strings.SplitN(s, PathSeparator, 2)
thisSel := selSegs[0]
nextSel := ""
if len(selSegs) > 1 {
nextSel = selSegs[1]
}
mapMatches := mapAccessRegex.FindStringSubmatch(s)
if len(mapMatches) > 0 {
if _, err := strconv.Atoi(mapMatches[2]); err != nil {
thisSel = mapMatches[1]
nextSel = "[" + mapMatches[2] + "]" + mapMatches[3]
if thisSel == "" {
thisSel = mapMatches[2]
nextSel = mapMatches[3]
}
if nextSel == "" {
selSegs = []string{"", ""}
} else if nextSel[0] == '.' {
nextSel = nextSel[1:]
}
}
}
return thisSel, nextSel
}
// access accesses the object using the selector and performs the
// appropriate action.
func access(current interface{}, selector string, value interface{}, isSet bool) interface{} {
thisSel, nextSel := getKey(selector)
indexes := []int{}
for strings.Contains(thisSel, "[") {
prevSel := thisSel
index := -1
index, thisSel = getIndex(thisSel)
indexes = append(indexes, index)
if prevSel == thisSel {
break
}
}
if curMap, ok := current.(Map); ok {
current = map[string]interface{}(curMap)
}
// get the object in question
switch current.(type) {
case map[string]interface{}:
curMSI := current.(map[string]interface{})
if nextSel == "" && isSet {
curMSI[thisSel] = value
return nil
}
_, ok := curMSI[thisSel].(map[string]interface{})
if !ok {
_, ok = curMSI[thisSel].(Map)
}
if (curMSI[thisSel] == nil || !ok) && len(indexes) == 0 && isSet {
curMSI[thisSel] = map[string]interface{}{}
}
current = curMSI[thisSel]
default:
current = nil
}
// do we need to access the item of an array?
if len(indexes) > 0 {
num := len(indexes)
for num > 0 {
num--
index := indexes[num]
indexes = indexes[:num]
if array, ok := interSlice(current); ok {
if index < len(array) {
current = array[index]
} else {
current = nil
break
}
}
}
}
if nextSel != "" {
current = access(current, nextSel, value, isSet)
}
return current
}
func interSlice(slice interface{}) ([]interface{}, bool) {
if array, ok := slice.([]interface{}); ok {
return array, ok
}
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
return nil, false
}
ret := make([]interface{}, s.Len())
for i := 0; i < s.Len(); i++ {
ret[i] = s.Index(i).Interface()
}
return ret, true
}
objx-0.5.2/accessors_test.go 0000664 0000000 0000000 00000013315 14570052437 0016045 0 ustar 00root root 0000000 0000000 package objx_test
import (
"testing"
"github.com/stretchr/objx"
"github.com/stretchr/testify/assert"
)
func TestAccessorsAccessGetSingleField(t *testing.T) {
m := objx.Map{"name": "Tyler"}
assert.Equal(t, "Tyler", m.Get("name").Data())
}
func TestAccessorsAccessGetSingleFieldInt(t *testing.T) {
m := objx.Map{"name": 10}
assert.Equal(t, 10, m.Get("name").Data())
}
func TestAccessorsAccessGetDeep(t *testing.T) {
m := objx.Map{
"name": objx.Map{
"first": "Tyler",
"last": "Bunnell",
"friends": []string{
"Capitol",
"Bollocks",
},
"ifriends": []interface{}{
"Capitol",
"Bollocks",
},
},
}
assert.Equal(t, "Tyler", m.Get("name.first").Data())
assert.Equal(t, "Bunnell", m.Get("name.last").Data())
assert.Equal(t, "Capitol", m.Get("name.friends[0]").Data())
assert.Equal(t, "Capitol", m.Get("name.ifriends[0]").Data())
}
func TestAccessorsAccessGetDeepDeep(t *testing.T) {
m := objx.Map{
"one": objx.Map{
"two": objx.Map{
"three": objx.Map{
"four": 4,
},
},
},
}
assert.Equal(t, 4, m.Get("one.two.three.four").Data())
assert.Equal(t, 4, m.Get("one[two][three][four]").Data())
}
func TestAccessorsGetWithComplexKey(t *testing.T) {
m := objx.Map{
"domains": objx.Map{
"example-dot-com": objx.Map{
"apex": "example",
},
"example.com": objx.Map{
"apex": "example",
},
},
}
assert.Equal(t, "example", m.Get("domains.example-dot-com.apex").Data())
assert.Equal(t, "example", m.Get("domains[example.com].apex").Data())
assert.Equal(t, "example", m.Get("domains[example.com][apex]").Data())
}
func TestAccessorsAccessGetInsideArray(t *testing.T) {
m := objx.Map{
"names": []interface{}{
objx.Map{
"first": "Tyler",
"last": "Bunnell",
},
objx.Map{
"first": "Capitol",
"last": "Bollocks",
},
},
}
assert.Equal(t, "Tyler", m.Get("names[0].first").Data())
assert.Equal(t, "Bunnell", m.Get("names[0].last").Data())
assert.Equal(t, "Capitol", m.Get("names[1].first").Data())
assert.Equal(t, "Bollocks", m.Get("names[1].last").Data())
assert.Nil(t, m.Get("names[2]").Data())
assert.Nil(t, m.Get("names[]").Data())
assert.Nil(t, m.Get("names1]]").Data())
assert.Nil(t, m.Get("names[1]]").Data())
assert.Nil(t, m.Get("names[[1]]").Data())
assert.Nil(t, m.Get("names[[1]").Data())
assert.Nil(t, m.Get("names[[1").Data())
}
func TestAccessorsGet(t *testing.T) {
m := objx.Map{"name": "Tyler"}
assert.Equal(t, "Tyler", m.Get("name").Data())
}
func TestAccessorsAccessSetSingleField(t *testing.T) {
m := objx.Map{"name": "Tyler"}
m.Set("name", "Mat")
m.Set("age", 29)
assert.Equal(t, m.Get("name").Data(), "Mat")
assert.Equal(t, m.Get("age").Data(), 29)
}
func TestAccessorsAccessSetSingleFieldNotExisting(t *testing.T) {
m := objx.Map{
"first": "Tyler",
"last": "Bunnell",
}
m.Set("name", "Mat")
assert.Equal(t, m.Get("name").Data(), "Mat")
}
func TestAccessorsAccessSetDeep(t *testing.T) {
m := objx.Map{
"name": objx.Map{
"first": "Tyler",
"last": "Bunnell",
},
}
m.Set("name.first", "Mat")
m.Set("name.last", "Ryer")
assert.Equal(t, "Mat", m.Get("name.first").Data())
assert.Equal(t, "Ryer", m.Get("name.last").Data())
}
func TestAccessorsAccessSetDeepDeep(t *testing.T) {
m := objx.Map{
"one": objx.Map{
"two": objx.Map{
"three": objx.Map{
"four": 4,
},
},
},
}
m.Set("one.two.three.four", 5)
assert.Equal(t, 5, m.Get("one.two.three.four").Data())
}
func TestAccessorsAccessSetDeepDeepWithoutExisting(t *testing.T) {
m := objx.Map{}
m.Set("one.two.three.four", 5)
m.Set("one.two.three.five", 6)
assert.Equal(t, 5, m.Get("one.two.three.four").Data())
assert.Equal(t, 6, m.Get("one.two.three.five").Data())
m.Set("one.two", 7)
assert.Equal(t, 7, m.Get("one.two").Data())
assert.Equal(t, nil, m.Get("one.two.three.four").Data())
m.Set("one.two.three", 8)
assert.Equal(t, 8, m.Get("one.two.three").Data())
}
func TestAccessorsAccessSetArray(t *testing.T) {
m := objx.Map{
"names": []interface{}{"Tyler"},
}
m.Set("names[0]", "Mat")
assert.Equal(t, "Mat", m.Get("names[0]").Data())
}
func TestAccessorsAccessSetInsideArray(t *testing.T) {
m := objx.Map{
"names": []interface{}{
objx.Map{
"first": "Tyler",
"last": "Bunnell",
},
objx.Map{
"first": "Capitol",
"last": "Bollocks",
},
},
}
m.Set("names[0].first", "Mat")
m.Set("names[0].last", "Ryer")
m.Set("names[1].first", "Captain")
m.Set("names[1].last", "Underpants")
assert.Equal(t, "Mat", m.Get("names[0].first").Data())
assert.Equal(t, "Ryer", m.Get("names[0].last").Data())
assert.Equal(t, "Captain", m.Get("names[1].first").Data())
assert.Equal(t, "Underpants", m.Get("names[1].last").Data())
}
func TestAccessorsSet(t *testing.T) {
m := objx.Map{"name": "Tyler"}
m.Set("name", "Mat")
assert.Equal(t, "Mat", m.Get("name").Data())
}
func TestAccessorsSetWithinObjxMapChild(t *testing.T) {
m, err := objx.FromJSON(`{"a": {"b": 1}}`)
assert.NoError(t, err)
m.Set("a.c", 2)
jsonConverted, err := m.JSON()
assert.NoError(t, err)
m = objx.New(map[string]interface{}{
"a": map[string]interface{}{
"b": 1,
},
})
m.Set("a.c", 2)
jsonNewObj, err := m.JSON()
assert.NoError(t, err)
assert.Equal(t, jsonConverted, jsonNewObj)
}
func TestAccessorsNested(t *testing.T) {
d := objx.MustFromJSON(`{"values":[["test", "test1"], ["test2", {"name":"Mat"}, {"names": ["Captain", "Mat"]}]]}`)
value := d.Get("values[0][0]").String()
assert.Equal(t, "test", value)
value = d.Get("values[0][1]").String()
assert.Equal(t, "test1", value)
value = d.Get("values[1][0]").String()
assert.Equal(t, "test2", value)
value = d.Get("values[1][1].name").String()
assert.Equal(t, "Mat", value)
value = d.Get("values[1][2].names[0]").String()
assert.Equal(t, "Captain", value)
}
objx-0.5.2/codegen/ 0000775 0000000 0000000 00000000000 14570052437 0014073 5 ustar 00root root 0000000 0000000 objx-0.5.2/codegen/array-access.txt 0000664 0000000 0000000 00000000530 14570052437 0017207 0 ustar 00root root 0000000 0000000 case []{1}:
a := object.([]{1})
if isSet {
a[index] = value.({1})
} else {
if index >= len(a) {
if panics {
panic(fmt.Sprintf("objx: Index %d is out of range because the []{1} only contains %d items.", index, len(a)))
}
return nil
} else {
return a[index]
}
}
objx-0.5.2/codegen/index.html 0000664 0000000 0000000 00000002614 14570052437 0016073 0 ustar 00root root 0000000 0000000
Codegen
Template
Use {x} as a placeholder for each argument.
Arguments (comma separated)
One block per line
Output
objx-0.5.2/codegen/template.txt 0000664 0000000 0000000 00000006743 14570052437 0016461 0 ustar 00root root 0000000 0000000 /*
{4} ({1} and []{1})
*/
// {4} gets the value as a {1}, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) {4}(optionalDefault ...{1}) {1} {
if s, ok := v.data.({1}); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return {3}
}
// Must{4} gets the value as a {1}.
//
// Panics if the object is not a {1}.
func (v *Value) Must{4}() {1} {
return v.data.({1})
}
// {4}Slice gets the value as a []{1}, returns the optionalDefault
// value or nil if the value is not a []{1}.
func (v *Value) {4}Slice(optionalDefault ...[]{1}) []{1} {
if s, ok := v.data.([]{1}); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// Must{4}Slice gets the value as a []{1}.
//
// Panics if the object is not a []{1}.
func (v *Value) Must{4}Slice() []{1} {
return v.data.([]{1})
}
// Is{4} gets whether the object contained is a {1} or not.
func (v *Value) Is{4}() bool {
_, ok := v.data.({1})
return ok
}
// Is{4}Slice gets whether the object contained is a []{1} or not.
func (v *Value) Is{4}Slice() bool {
_, ok := v.data.([]{1})
return ok
}
// Each{4} calls the specified callback for each object
// in the []{1}.
//
// Panics if the object is the wrong type.
func (v *Value) Each{4}(callback func(int, {1}) bool) *Value {
for index, val := range v.Must{4}Slice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// Where{4} uses the specified decider function to select items
// from the []{1}. The object contained in the result will contain
// only the selected items.
func (v *Value) Where{4}(decider func(int, {1}) bool) *Value {
var selected []{1}
v.Each{4}(func(index int, val {1}) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data:selected}
}
// Group{4} uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]{1}.
func (v *Value) Group{4}(grouper func(int, {1}) string) *Value {
groups := make(map[string][]{1})
v.Each{4}(func(index int, val {1}) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]{1}, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data:groups}
}
// Replace{4} uses the specified function to replace each {1}s
// by iterating each item. The data in the returned result will be a
// []{1} containing the replaced items.
func (v *Value) Replace{4}(replacer func(int, {1}) {1}) *Value {
arr := v.Must{4}Slice()
replaced := make([]{1}, len(arr))
v.Each{4}(func(index int, val {1}) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data:replaced}
}
// Collect{4} uses the specified collector function to collect a value
// for each of the {1}s in the slice. The data returned will be a
// []interface{}.
func (v *Value) Collect{4}(collector func(int, {1}) interface{}) *Value {
arr := v.Must{4}Slice()
collected := make([]interface{}, len(arr))
v.Each{4}(func(index int, val {1}) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data:collected}
}
objx-0.5.2/codegen/template_test.txt 0000664 0000000 0000000 00000007260 14570052437 0017513 0 ustar 00root root 0000000 0000000 /*
Tests for {4} ({1} and []{1})
*/
func Test{4}(t *testing.T) {
val := {1}({2})
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").{4}())
assert.Equal(t, val, m.Get("value").Must{4}())
assert.Equal(t, {1}({3}), m.Get("nothing").{4}())
assert.Equal(t, val, m.Get("nothing").{4}({2}))
assert.Panics(t, func() {
m.Get("age").Must{4}()
})
}
func Test{4}Slice(t *testing.T) {
val := {1}({2})
m := objx.Map{"value": []{1}{ val }, "nothing": nil}
assert.Equal(t, val, m.Get("value").{4}Slice()[0])
assert.Equal(t, val, m.Get("value").Must{4}Slice()[0])
assert.Equal(t, []{1}(nil), m.Get("nothing").{4}Slice())
assert.Equal(t, val, m.Get("nothing").{4}Slice([]{1}{{1}({2})})[0])
assert.Panics(t, func() {
m.Get("nothing").Must{4}Slice()
})
}
func TestIs{4}(t *testing.T) {
m := objx.Map{"data": {1}({2})}
assert.True(t, m.Get("data").Is{4}())
}
func TestIs{4}Slice(t *testing.T) {
m := objx.Map{"data": []{1}{{1}({2})}}
assert.True(t, m.Get("data").Is{4}Slice())
}
func TestEach{4}(t *testing.T) {
m := objx.Map{"data": []{1}{{1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2})}}
count := 0
replacedVals := make([]{1}, 0)
assert.Equal(t, m.Get("data"), m.Get("data").Each{4}(func(i int, val {1}) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").Must{4}Slice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").Must{4}Slice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").Must{4}Slice()[2])
}
func TestWhere{4}(t *testing.T) {
m := objx.Map{"data": []{1}{{1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2})}}
selected := m.Get("data").Where{4}(func(i int, val {1}) bool {
return i%2 == 0
}).Must{4}Slice()
assert.Equal(t, 3, len(selected))
}
func TestGroup{4}(t *testing.T) {
m := objx.Map{"data": []{1}{{1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2})}}
grouped := m.Get("data").Group{4}(func(i int, val {1}) string {
return fmt.Sprintf("%v", i%2==0)
}).Data().(map[string][]{1})
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplace{4}(t *testing.T) {
m := objx.Map{"data": []{1}{{1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2})}}
rawArr := m.Get("data").Must{4}Slice()
replaced := m.Get("data").Replace{4}(func(index int, val {1}) {1} {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.Must{4}Slice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollect{4}(t *testing.T) {
m := objx.Map{"data": []{1}{{1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2})}}
collected := m.Get("data").Collect{4}(func(index int, val {1}) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
objx-0.5.2/codegen/types_list.txt 0000664 0000000 0000000 00000001014 14570052437 0017027 0 ustar 00root root 0000000 0000000 Interface,interface{},"something",nil,Inter
ObjxMap,(objx.Map),objx.New(1),objx.New(nil),ObjxMap
Bool,bool,true,false,Bool
String,string,"hello","",Str
Int,int,1,0,Int
Int8,int8,1,0,Int8
Int16,int16,1,0,Int16
Int32,int32,1,0,Int32
Int64,int64,1,0,Int64
Uint,uint,1,0,Uint
Uint8,uint8,1,0,Uint8
Uint16,uint16,1,0,Uint16
Uint32,uint32,1,0,Uint32
Uint64,uint64,1,0,Uint64
Uintptr,uintptr,1,0,Uintptr
Float32,float32,1,0,Float32
Float64,float64,1,0,Float64
Complex64,complex64,1,0,Complex64
Complex128,complex128,1,0,Complex128
objx-0.5.2/conversions.go 0000664 0000000 0000000 00000015567 14570052437 0015404 0 ustar 00root root 0000000 0000000 package objx
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/url"
"strconv"
)
// SignatureSeparator is the character that is used to
// separate the Base64 string from the security signature.
const SignatureSeparator = "_"
// URLValuesSliceKeySuffix is the character that is used to
// specify a suffix for slices parsed by URLValues.
// If the suffix is set to "[i]", then the index of the slice
// is used in place of i
// Ex: Suffix "[]" would have the form a[]=b&a[]=c
// OR Suffix "[i]" would have the form a[0]=b&a[1]=c
// OR Suffix "" would have the form a=b&a=c
var urlValuesSliceKeySuffix = "[]"
const (
URLValuesSliceKeySuffixEmpty = ""
URLValuesSliceKeySuffixArray = "[]"
URLValuesSliceKeySuffixIndex = "[i]"
)
// SetURLValuesSliceKeySuffix sets the character that is used to
// specify a suffix for slices parsed by URLValues.
// If the suffix is set to "[i]", then the index of the slice
// is used in place of i
// Ex: Suffix "[]" would have the form a[]=b&a[]=c
// OR Suffix "[i]" would have the form a[0]=b&a[1]=c
// OR Suffix "" would have the form a=b&a=c
func SetURLValuesSliceKeySuffix(s string) error {
if s == URLValuesSliceKeySuffixEmpty || s == URLValuesSliceKeySuffixArray || s == URLValuesSliceKeySuffixIndex {
urlValuesSliceKeySuffix = s
return nil
}
return errors.New("objx: Invalid URLValuesSliceKeySuffix provided.")
}
// JSON converts the contained object to a JSON string
// representation
func (m Map) JSON() (string, error) {
for k, v := range m {
m[k] = cleanUp(v)
}
result, err := json.Marshal(m)
if err != nil {
err = errors.New("objx: JSON encode failed with: " + err.Error())
}
return string(result), err
}
func cleanUpInterfaceArray(in []interface{}) []interface{} {
result := make([]interface{}, len(in))
for i, v := range in {
result[i] = cleanUp(v)
}
return result
}
func cleanUpInterfaceMap(in map[interface{}]interface{}) Map {
result := Map{}
for k, v := range in {
result[fmt.Sprintf("%v", k)] = cleanUp(v)
}
return result
}
func cleanUpStringMap(in map[string]interface{}) Map {
result := Map{}
for k, v := range in {
result[k] = cleanUp(v)
}
return result
}
func cleanUpMSIArray(in []map[string]interface{}) []Map {
result := make([]Map, len(in))
for i, v := range in {
result[i] = cleanUpStringMap(v)
}
return result
}
func cleanUpMapArray(in []Map) []Map {
result := make([]Map, len(in))
for i, v := range in {
result[i] = cleanUpStringMap(v)
}
return result
}
func cleanUp(v interface{}) interface{} {
switch v := v.(type) {
case []interface{}:
return cleanUpInterfaceArray(v)
case []map[string]interface{}:
return cleanUpMSIArray(v)
case map[interface{}]interface{}:
return cleanUpInterfaceMap(v)
case Map:
return cleanUpStringMap(v)
case []Map:
return cleanUpMapArray(v)
default:
return v
}
}
// MustJSON converts the contained object to a JSON string
// representation and panics if there is an error
func (m Map) MustJSON() string {
result, err := m.JSON()
if err != nil {
panic(err.Error())
}
return result
}
// Base64 converts the contained object to a Base64 string
// representation of the JSON string representation
func (m Map) Base64() (string, error) {
var buf bytes.Buffer
jsonData, err := m.JSON()
if err != nil {
return "", err
}
encoder := base64.NewEncoder(base64.StdEncoding, &buf)
_, _ = encoder.Write([]byte(jsonData))
_ = encoder.Close()
return buf.String(), nil
}
// MustBase64 converts the contained object to a Base64 string
// representation of the JSON string representation and panics
// if there is an error
func (m Map) MustBase64() string {
result, err := m.Base64()
if err != nil {
panic(err.Error())
}
return result
}
// SignedBase64 converts the contained object to a Base64 string
// representation of the JSON string representation and signs it
// using the provided key.
func (m Map) SignedBase64(key string) (string, error) {
base64, err := m.Base64()
if err != nil {
return "", err
}
sig := HashWithKey(base64, key)
return base64 + SignatureSeparator + sig, nil
}
// MustSignedBase64 converts the contained object to a Base64 string
// representation of the JSON string representation and signs it
// using the provided key and panics if there is an error
func (m Map) MustSignedBase64(key string) string {
result, err := m.SignedBase64(key)
if err != nil {
panic(err.Error())
}
return result
}
/*
URL Query
------------------------------------------------
*/
// URLValues creates a url.Values object from an Obj. This
// function requires that the wrapped object be a map[string]interface{}
func (m Map) URLValues() url.Values {
vals := make(url.Values)
m.parseURLValues(m, vals, "")
return vals
}
func (m Map) parseURLValues(queryMap Map, vals url.Values, key string) {
useSliceIndex := false
if urlValuesSliceKeySuffix == "[i]" {
useSliceIndex = true
}
for k, v := range queryMap {
val := &Value{data: v}
switch {
case val.IsObjxMap():
if key == "" {
m.parseURLValues(val.ObjxMap(), vals, k)
} else {
m.parseURLValues(val.ObjxMap(), vals, key+"["+k+"]")
}
case val.IsObjxMapSlice():
sliceKey := k
if key != "" {
sliceKey = key + "[" + k + "]"
}
if useSliceIndex {
for i, sv := range val.MustObjxMapSlice() {
sk := sliceKey + "[" + strconv.FormatInt(int64(i), 10) + "]"
m.parseURLValues(sv, vals, sk)
}
} else {
sliceKey = sliceKey + urlValuesSliceKeySuffix
for _, sv := range val.MustObjxMapSlice() {
m.parseURLValues(sv, vals, sliceKey)
}
}
case val.IsMSISlice():
sliceKey := k
if key != "" {
sliceKey = key + "[" + k + "]"
}
if useSliceIndex {
for i, sv := range val.MustMSISlice() {
sk := sliceKey + "[" + strconv.FormatInt(int64(i), 10) + "]"
m.parseURLValues(New(sv), vals, sk)
}
} else {
sliceKey = sliceKey + urlValuesSliceKeySuffix
for _, sv := range val.MustMSISlice() {
m.parseURLValues(New(sv), vals, sliceKey)
}
}
case val.IsStrSlice(), val.IsBoolSlice(),
val.IsFloat32Slice(), val.IsFloat64Slice(),
val.IsIntSlice(), val.IsInt8Slice(), val.IsInt16Slice(), val.IsInt32Slice(), val.IsInt64Slice(),
val.IsUintSlice(), val.IsUint8Slice(), val.IsUint16Slice(), val.IsUint32Slice(), val.IsUint64Slice():
sliceKey := k
if key != "" {
sliceKey = key + "[" + k + "]"
}
if useSliceIndex {
for i, sv := range val.StringSlice() {
sk := sliceKey + "[" + strconv.FormatInt(int64(i), 10) + "]"
vals.Set(sk, sv)
}
} else {
sliceKey = sliceKey + urlValuesSliceKeySuffix
vals[sliceKey] = val.StringSlice()
}
default:
if key == "" {
vals.Set(k, val.String())
} else {
vals.Set(key+"["+k+"]", val.String())
}
}
}
}
// URLQuery gets an encoded URL query representing the given
// Obj. This function requires that the wrapped object be a
// map[string]interface{}
func (m Map) URLQuery() (string, error) {
return m.URLValues().Encode(), nil
}
objx-0.5.2/conversions_test.go 0000664 0000000 0000000 00000012516 14570052437 0016432 0 ustar 00root root 0000000 0000000 package objx_test
import (
"net/url"
"testing"
"github.com/stretchr/objx"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestConversionJSON(t *testing.T) {
jsonString := `{"name":"Mat"}`
o := objx.MustFromJSON(jsonString)
result, err := o.JSON()
require.NoError(t, err)
assert.Equal(t, jsonString, result)
assert.Equal(t, jsonString, o.MustJSON())
i := objx.Map{
"a": map[interface{}]interface{}{"b": objx.Map{"c": map[interface{}]interface{}{"d": "e"}},
"f": []objx.Map{{"g": map[interface{}]interface{}{"h": "i"}}},
"j": []map[string]interface{}{{"k": map[interface{}]interface{}{"l": "m"}}},
"n": []interface{}{objx.Map{"o": "p"}},
},
}
jsonString = `{"a":{"b":{"c":{"d":"e"}},"f":[{"g":{"h":"i"}}],"j":[{"k":{"l":"m"}}],"n":[{"o":"p"}]}}`
result, err = i.JSON()
require.NoError(t, err)
assert.Equal(t, jsonString, result)
assert.Equal(t, jsonString, i.MustJSON())
}
func TestConversionJSONWithError(t *testing.T) {
o := objx.MSI()
o["test"] = func() {}
assert.Panics(t, func() {
o.MustJSON()
})
_, err := o.JSON()
assert.Error(t, err)
}
func TestConversionBase64(t *testing.T) {
o := objx.Map{"name": "Mat"}
result, err := o.Base64()
require.NoError(t, err)
assert.Equal(t, "eyJuYW1lIjoiTWF0In0=", result)
assert.Equal(t, "eyJuYW1lIjoiTWF0In0=", o.MustBase64())
}
func TestConversionBase64WithError(t *testing.T) {
o := objx.MSI()
o["test"] = func() {}
assert.Panics(t, func() {
o.MustBase64()
})
_, err := o.Base64()
assert.Error(t, err)
}
func TestConversionSignedBase64(t *testing.T) {
o := objx.Map{"name": "Mat"}
result, err := o.SignedBase64("key")
require.NoError(t, err)
assert.Equal(t, "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6", result)
assert.Equal(t, "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6", o.MustSignedBase64("key"))
}
func TestConversionSignedBase64WithError(t *testing.T) {
o := objx.MSI()
o["test"] = func() {}
assert.Panics(t, func() {
o.MustSignedBase64("key")
})
_, err := o.SignedBase64("key")
assert.Error(t, err)
}
func TestConversionURLValues(t *testing.T) {
m := getURLQueryMap()
u := m.URLValues()
assert.Equal(t, url.Values{
"abc": []string{"123"},
"name": []string{"Mat"},
"data[age]": []string{"30"},
"data[height]": []string{"162"},
"data[arr][]": []string{"1", "2"},
"stats[]": []string{"1", "2"},
"bools[]": []string{"true", "false"},
"mapSlice[][age]": []string{"40"},
"mapSlice[][height]": []string{"152"},
"msiData[age]": []string{"30"},
"msiData[height]": []string{"162"},
"msiData[arr][]": []string{"1", "2"},
"msiSlice[][age]": []string{"40"},
"msiSlice[][height]": []string{"152"},
}, u)
}
func TestConversionURLQuery(t *testing.T) {
m := getURLQueryMap()
u, err := m.URLQuery()
assert.Nil(t, err)
require.NotNil(t, u)
ue, err := url.QueryUnescape(u)
assert.Nil(t, err)
require.NotNil(t, ue)
assert.Equal(t, "abc=123&bools[]=true&bools[]=false&data[age]=30&data[arr][]=1&data[arr][]=2&data[height]=162&mapSlice[][age]=40&mapSlice[][height]=152&msiData[age]=30&msiData[arr][]=1&msiData[arr][]=2&msiData[height]=162&msiSlice[][age]=40&msiSlice[][height]=152&name=Mat&stats[]=1&stats[]=2", ue)
}
func TestConversionURLQueryNoSliceKeySuffix(t *testing.T) {
m := getURLQueryMap()
err := objx.SetURLValuesSliceKeySuffix(objx.URLValuesSliceKeySuffixEmpty)
require.Nil(t, err)
u, err := m.URLQuery()
assert.Nil(t, err)
require.NotNil(t, u)
ue, err := url.QueryUnescape(u)
assert.Nil(t, err)
require.NotNil(t, ue)
assert.Equal(t, "abc=123&bools=true&bools=false&data[age]=30&data[arr]=1&data[arr]=2&data[height]=162&mapSlice[age]=40&mapSlice[height]=152&msiData[age]=30&msiData[arr]=1&msiData[arr]=2&msiData[height]=162&msiSlice[age]=40&msiSlice[height]=152&name=Mat&stats=1&stats=2", ue)
}
func TestConversionURLQueryIndexSliceKeySuffix(t *testing.T) {
m := getURLQueryMap()
m.Set("mapSlice", []objx.Map{{"age": 40, "sex": "male"}, {"height": 152}})
err := objx.SetURLValuesSliceKeySuffix(objx.URLValuesSliceKeySuffixIndex)
require.Nil(t, err)
u, err := m.URLQuery()
assert.Nil(t, err)
require.NotNil(t, u)
ue, err := url.QueryUnescape(u)
assert.Nil(t, err)
require.NotNil(t, ue)
assert.Equal(t, "abc=123&bools[0]=true&bools[1]=false&data[age]=30&data[arr][0]=1&data[arr][1]=2&data[height]=162&mapSlice[0][age]=40&mapSlice[0][sex]=male&mapSlice[1][height]=152&msiData[age]=30&msiData[arr][0]=1&msiData[arr][1]=2&msiData[height]=162&msiSlice[0][age]=40&msiSlice[1][height]=152&name=Mat&stats[0]=1&stats[1]=2", ue)
}
func TestValidityURLQuerySliceKeySuffix(t *testing.T) {
err := objx.SetURLValuesSliceKeySuffix("")
assert.Nil(t, err)
err = objx.SetURLValuesSliceKeySuffix("[]")
assert.Nil(t, err)
err = objx.SetURLValuesSliceKeySuffix("[i]")
assert.Nil(t, err)
err = objx.SetURLValuesSliceKeySuffix("{}")
assert.Error(t, err)
}
func getURLQueryMap() objx.Map {
return objx.Map{
"abc": 123,
"name": "Mat",
"data": objx.Map{"age": 30, "height": 162, "arr": []int{1, 2}},
"mapSlice": []objx.Map{{"age": 40}, {"height": 152}},
"msiData": map[string]interface{}{"age": 30, "height": 162, "arr": []int{1, 2}},
"msiSlice": []map[string]interface{}{{"age": 40}, {"height": 152}},
"stats": []string{"1", "2"},
"bools": []bool{true, false},
}
}
objx-0.5.2/doc.go 0000664 0000000 0000000 00000004103 14570052437 0013561 0 ustar 00root root 0000000 0000000 /*
Package objx provides utilities for dealing with maps, slices, JSON and other data.
# Overview
Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes
a powerful `Get` method (among others) that allows you to easily and quickly get
access to data within the map, without having to worry too much about type assertions,
missing data, default values etc.
# Pattern
Objx uses a predictable pattern to make access data from within `map[string]interface{}` easy.
Call one of the `objx.` functions to create your `objx.Map` to get going:
m, err := objx.FromJSON(json)
NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong,
the rest will be optimistic and try to figure things out without panicking.
Use `Get` to access the value you're interested in. You can use dot and array
notation too:
m.Get("places[0].latlng")
Once you have sought the `Value` you're interested in, you can use the `Is*` methods to determine its type.
if m.Get("code").IsStr() { // Your code... }
Or you can just assume the type, and use one of the strong type methods to extract the real value:
m.Get("code").Int()
If there's no value there (or if it's the wrong type) then a default value will be returned,
or you can be explicit about the default value.
Get("code").Int(-1)
If you're dealing with a slice of data as a value, Objx provides many useful methods for iterating,
manipulating and selecting that data. You can find out more by exploring the index below.
# Reading data
A simple example of how to use Objx:
// Use MustFromJSON to make an objx.Map from some JSON
m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`)
// Get the details
name := m.Get("name").Str()
age := m.Get("age").Int()
// Get their nickname (or use their name if they don't have one)
nickname := m.Get("nickname").Str(name)
# Ranging
Since `objx.Map` is a `map[string]interface{}` you can treat it as such.
For example, to `range` the data, do what you would expect:
m := objx.MustFromJSON(json)
for key, value := range m {
// Your code...
}
*/
package objx
objx-0.5.2/fixture_test.go 0000664 0000000 0000000 00000004322 14570052437 0015544 0 ustar 00root root 0000000 0000000 package objx_test
import (
"testing"
"github.com/stretchr/objx"
"github.com/stretchr/testify/assert"
)
var fixtures = []struct {
// name is the name of the fixture (used for reporting
// failures)
name string
// data is the JSON data to be worked on
data string
// get is the argument(s) to pass to Get
get interface{}
// output is the expected output
output interface{}
}{
{
name: "Simple get",
data: `{"name": "Mat"}`,
get: "name",
output: "Mat",
},
{
name: "Get with dot notation",
data: `{"address": {"city": "Boulder"}}`,
get: "address.city",
output: "Boulder",
},
{
name: "Deep get with dot notation",
data: `{"one": {"two": {"three": {"four": "hello"}}}}`,
get: "one.two.three.four",
output: "hello",
},
{
name: "Get missing with dot notation",
data: `{"one": {"two": {"three": {"four": "hello"}}}}`,
get: "one.ten",
output: nil,
},
{
name: "Get with array notation",
data: `{"tags": ["one", "two", "three"]}`,
get: "tags[1]",
output: "two",
},
{
name: "Get with array and dot notation",
data: `{"types": { "tags": ["one", "two", "three"]}}`,
get: "types.tags[1]",
output: "two",
},
{
name: "Get with array and dot notation - field after array",
data: `{"tags": [{"name":"one"}, {"name":"two"}, {"name":"three"}]}`,
get: "tags[1].name",
output: "two",
},
{
name: "Complex get with array and dot notation",
data: `{"tags": [{"list": [{"one":"pizza"}]}]}`,
get: "tags[0].list[0].one",
output: "pizza",
},
{
name: "Get field from within string should be nil",
data: `{"name":"Tyler"}`,
get: "name.something",
output: nil,
},
{
name: "Get field from within string (using array accessor) should be nil",
data: `{"numbers":["one", "two", "three"]}`,
get: "numbers[0].nope",
output: nil,
},
}
func TestFixtures(t *testing.T) {
for _, fixture := range fixtures {
m := objx.MustFromJSON(fixture.data)
// get the value
t.Logf("Running get fixture: \"%s\" (%v)", fixture.name, fixture)
value := m.Get(fixture.get.(string))
// make sure it matches
assert.Equal(t, fixture.output, value.Data(),
"Get fixture \"%s\" failed: %v", fixture.name, fixture,
)
}
}
objx-0.5.2/go.mod 0000664 0000000 0000000 00000000424 14570052437 0013575 0 ustar 00root root 0000000 0000000 module github.com/stretchr/objx
go 1.20
require github.com/stretchr/testify v1.8.4
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
exclude github.com/stretchr/testify v1.8.0
objx-0.5.2/go.sum 0000664 0000000 0000000 00000001710 14570052437 0013621 0 ustar 00root root 0000000 0000000 github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
objx-0.5.2/map.go 0000664 0000000 0000000 00000013303 14570052437 0013573 0 ustar 00root root 0000000 0000000 package objx
import (
"encoding/base64"
"encoding/json"
"errors"
"io/ioutil"
"net/url"
"strings"
)
// MSIConvertable is an interface that defines methods for converting your
// custom types to a map[string]interface{} representation.
type MSIConvertable interface {
// MSI gets a map[string]interface{} (msi) representing the
// object.
MSI() map[string]interface{}
}
// Map provides extended functionality for working with
// untyped data, in particular map[string]interface (msi).
type Map map[string]interface{}
// Value returns the internal value instance
func (m Map) Value() *Value {
return &Value{data: m}
}
// Nil represents a nil Map.
var Nil = New(nil)
// New creates a new Map containing the map[string]interface{} in the data argument.
// If the data argument is not a map[string]interface, New attempts to call the
// MSI() method on the MSIConvertable interface to create one.
func New(data interface{}) Map {
if _, ok := data.(map[string]interface{}); !ok {
if converter, ok := data.(MSIConvertable); ok {
data = converter.MSI()
} else {
return nil
}
}
return Map(data.(map[string]interface{}))
}
// MSI creates a map[string]interface{} and puts it inside a new Map.
//
// The arguments follow a key, value pattern.
//
// Returns nil if any key argument is non-string or if there are an odd number of arguments.
//
// # Example
//
// To easily create Maps:
//
// m := objx.MSI("name", "Mat", "age", 29, "subobj", objx.MSI("active", true))
//
// // creates an Map equivalent to
// m := objx.Map{"name": "Mat", "age": 29, "subobj": objx.Map{"active": true}}
func MSI(keyAndValuePairs ...interface{}) Map {
newMap := Map{}
keyAndValuePairsLen := len(keyAndValuePairs)
if keyAndValuePairsLen%2 != 0 {
return nil
}
for i := 0; i < keyAndValuePairsLen; i = i + 2 {
key := keyAndValuePairs[i]
value := keyAndValuePairs[i+1]
// make sure the key is a string
keyString, keyStringOK := key.(string)
if !keyStringOK {
return nil
}
newMap[keyString] = value
}
return newMap
}
// ****** Conversion Constructors
// MustFromJSON creates a new Map containing the data specified in the
// jsonString.
//
// Panics if the JSON is invalid.
func MustFromJSON(jsonString string) Map {
o, err := FromJSON(jsonString)
if err != nil {
panic("objx: MustFromJSON failed with error: " + err.Error())
}
return o
}
// MustFromJSONSlice creates a new slice of Map containing the data specified in the
// jsonString. Works with jsons with a top level array
//
// Panics if the JSON is invalid.
func MustFromJSONSlice(jsonString string) []Map {
slice, err := FromJSONSlice(jsonString)
if err != nil {
panic("objx: MustFromJSONSlice failed with error: " + err.Error())
}
return slice
}
// FromJSON creates a new Map containing the data specified in the
// jsonString.
//
// Returns an error if the JSON is invalid.
func FromJSON(jsonString string) (Map, error) {
var m Map
err := json.Unmarshal([]byte(jsonString), &m)
if err != nil {
return Nil, err
}
return m, nil
}
// FromJSONSlice creates a new slice of Map containing the data specified in the
// jsonString. Works with jsons with a top level array
//
// Returns an error if the JSON is invalid.
func FromJSONSlice(jsonString string) ([]Map, error) {
var slice []Map
err := json.Unmarshal([]byte(jsonString), &slice)
if err != nil {
return nil, err
}
return slice, nil
}
// FromBase64 creates a new Obj containing the data specified
// in the Base64 string.
//
// The string is an encoded JSON string returned by Base64
func FromBase64(base64String string) (Map, error) {
decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(base64String))
decoded, err := ioutil.ReadAll(decoder)
if err != nil {
return nil, err
}
return FromJSON(string(decoded))
}
// MustFromBase64 creates a new Obj containing the data specified
// in the Base64 string and panics if there is an error.
//
// The string is an encoded JSON string returned by Base64
func MustFromBase64(base64String string) Map {
result, err := FromBase64(base64String)
if err != nil {
panic("objx: MustFromBase64 failed with error: " + err.Error())
}
return result
}
// FromSignedBase64 creates a new Obj containing the data specified
// in the Base64 string.
//
// The string is an encoded JSON string returned by SignedBase64
func FromSignedBase64(base64String, key string) (Map, error) {
parts := strings.Split(base64String, SignatureSeparator)
if len(parts) != 2 {
return nil, errors.New("objx: Signed base64 string is malformed")
}
sig := HashWithKey(parts[0], key)
if parts[1] != sig {
return nil, errors.New("objx: Signature for base64 data does not match")
}
return FromBase64(parts[0])
}
// MustFromSignedBase64 creates a new Obj containing the data specified
// in the Base64 string and panics if there is an error.
//
// The string is an encoded JSON string returned by Base64
func MustFromSignedBase64(base64String, key string) Map {
result, err := FromSignedBase64(base64String, key)
if err != nil {
panic("objx: MustFromSignedBase64 failed with error: " + err.Error())
}
return result
}
// FromURLQuery generates a new Obj by parsing the specified
// query.
//
// For queries with multiple values, the first value is selected.
func FromURLQuery(query string) (Map, error) {
vals, err := url.ParseQuery(query)
if err != nil {
return nil, err
}
m := Map{}
for k, vals := range vals {
m[k] = vals[0]
}
return m, nil
}
// MustFromURLQuery generates a new Obj by parsing the specified
// query.
//
// For queries with multiple values, the first value is selected.
//
// Panics if it encounters an error
func MustFromURLQuery(query string) Map {
o, err := FromURLQuery(query)
if err != nil {
panic("objx: MustFromURLQuery failed with error: " + err.Error())
}
return o
}
objx-0.5.2/map_test.go 0000664 0000000 0000000 00000012572 14570052437 0014641 0 ustar 00root root 0000000 0000000 package objx_test
import (
"testing"
"github.com/stretchr/objx"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var TestMap = objx.Map{
"name": "Tyler",
"address": objx.Map{
"city": "Salt Lake City",
"state": "UT",
},
"numbers": []interface{}{"one", "two", "three", "four", "five"},
}
type Convertable struct {
name string
}
type Unconvertable struct {
name string
}
func (c *Convertable) MSI() map[string]interface{} {
return objx.Map{"name": c.name}
}
func TestMapCreation(t *testing.T) {
o := objx.New(nil)
assert.Nil(t, o)
o = objx.New("Tyler")
assert.Nil(t, o)
unconvertable := &Unconvertable{name: "Tyler"}
o = objx.New(unconvertable)
assert.Nil(t, o)
convertable := &Convertable{name: "Tyler"}
o = objx.New(convertable)
require.NotNil(t, convertable)
assert.Equal(t, "Tyler", o["name"])
o = objx.MSI()
assert.NotNil(t, o)
o = objx.MSI("name", "Tyler")
require.NotNil(t, o)
assert.Equal(t, o["name"], "Tyler")
o = objx.MSI(1, "a")
assert.Nil(t, o)
o = objx.MSI("a")
assert.Nil(t, o)
o = objx.MSI("a", "b", "c")
assert.Nil(t, o)
}
func TestMapValue(t *testing.T) {
m := objx.Map{
"a": 1,
}
v := m.Value()
assert.Equal(t, m, v.ObjxMap())
}
func TestMapMustFromJSONWithError(t *testing.T) {
_, err := objx.FromJSON(`"name":"Mat"}`)
assert.Error(t, err)
}
func TestMapFromJSON(t *testing.T) {
o := objx.MustFromJSON(`{"name":"Mat"}`)
require.NotNil(t, o)
assert.Equal(t, "Mat", o["name"])
}
func TestMapFromJSONWithError(t *testing.T) {
var m objx.Map
assert.Panics(t, func() {
m = objx.MustFromJSON(`"name":"Mat"}`)
})
assert.Nil(t, m)
}
func TestConversionJSONInt(t *testing.T) {
jsonString :=
`{
"a": 1,
"b": {
"data": 1
},
"c": [1],
"d": [[1]]
}`
m, err := objx.FromJSON(jsonString)
assert.Nil(t, err)
require.NotNil(t, m)
assert.Equal(t, 1, m.Get("a").Int())
assert.Equal(t, 1, m.Get("b.data").Int())
assert.True(t, m.Get("c").IsInterSlice())
assert.Equal(t, float64(1), m.Get("c").InterSlice()[0])
assert.True(t, m.Get("d").IsInterSlice())
assert.Equal(t, []interface{}{float64(1)}, m.Get("d").InterSlice()[0])
}
func TestJSONSliceInt(t *testing.T) {
jsonString :=
`{
"a": [
{"b": 1},
{"c": 2}
]
}`
m, err := objx.FromJSON(jsonString)
assert.Nil(t, err)
require.NotNil(t, m)
assert.Equal(t, []objx.Map{{"b": float64(1)}, {"c": float64(2)}}, m.Get("a").ObjxMapSlice())
}
func TestJSONSliceMixed(t *testing.T) {
jsonString :=
`{
"a": [
{"b": 1},
"a"
]
}`
m, err := objx.FromJSON(jsonString)
assert.Nil(t, err)
require.NotNil(t, m)
assert.Nil(t, m.Get("a").ObjxMapSlice())
}
func TestMapFromBase64String(t *testing.T) {
base64String := "eyJuYW1lIjoiTWF0In0="
o, err := objx.FromBase64(base64String)
require.NoError(t, err)
assert.Equal(t, o.Get("name").Str(), "Mat")
assert.Equal(t, objx.MustFromBase64(base64String).Get("name").Str(), "Mat")
}
func TestMapFromBase64StringWithError(t *testing.T) {
base64String := "eyJuYW1lIjoiTWFasd0In0="
_, err := objx.FromBase64(base64String)
assert.Error(t, err)
assert.Panics(t, func() {
objx.MustFromBase64(base64String)
})
}
func TestMapFromSignedBase64String(t *testing.T) {
base64String := "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6"
o, err := objx.FromSignedBase64(base64String, "key")
require.NoError(t, err)
assert.Equal(t, o.Get("name").Str(), "Mat")
assert.Equal(t, objx.MustFromSignedBase64(base64String, "key").Get("name").Str(), "Mat")
}
func TestMapFromSignedBase64StringWithError(t *testing.T) {
base64String := "eyJuYW1lasdIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6"
_, err := objx.FromSignedBase64(base64String, "key")
assert.Error(t, err)
assert.Panics(t, func() {
objx.MustFromSignedBase64(base64String, "key")
})
base64String = "eyJuYW1lasdIjoiTWF0In0=67ee82916f90b2c0d68c903266e8998c9ef0c3d6"
_, err = objx.FromSignedBase64(base64String, "key")
assert.Error(t, err)
assert.Panics(t, func() {
objx.MustFromSignedBase64(base64String, "key")
})
base64String = "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6_junk"
_, err = objx.FromSignedBase64(base64String, "key")
assert.Error(t, err)
assert.Panics(t, func() {
objx.MustFromSignedBase64(base64String, "key")
})
}
func TestMapFromURLQuery(t *testing.T) {
m, err := objx.FromURLQuery("name=tyler&state=UT")
assert.NoError(t, err)
require.NotNil(t, m)
assert.Equal(t, "tyler", m.Get("name").Str())
assert.Equal(t, "UT", m.Get("state").Str())
}
func TestMapMustFromURLQuery(t *testing.T) {
m := objx.MustFromURLQuery("name=tyler&state=UT")
require.NotNil(t, m)
assert.Equal(t, "tyler", m.Get("name").Str())
assert.Equal(t, "UT", m.Get("state").Str())
}
func TestMapFromURLQueryWithError(t *testing.T) {
m, err := objx.FromURLQuery("%")
assert.Error(t, err)
assert.Nil(t, m)
assert.Panics(t, func() {
objx.MustFromURLQuery("%")
})
}
func TestJSONTopLevelSlice(t *testing.T) {
slice, err := objx.FromJSONSlice(`[{"id": 10000001}, {"id": 42}]`)
assert.NoError(t, err)
require.Len(t, slice, 2)
assert.Equal(t, 10000001, slice[0].Get("id").MustInt())
assert.Equal(t, 42, slice[1].Get("id").MustInt())
}
func TestJSONTopLevelSliceWithError(t *testing.T) {
slice, err := objx.FromJSONSlice(`{"id": 10000001}`)
assert.Error(t, err)
assert.Nil(t, slice)
assert.Panics(t, func() {
_ = objx.MustFromJSONSlice(`{"id": 10000001}`)
})
}
objx-0.5.2/mutations.go 0000664 0000000 0000000 00000004042 14570052437 0015041 0 ustar 00root root 0000000 0000000 package objx
// Exclude returns a new Map with the keys in the specified []string
// excluded.
func (m Map) Exclude(exclude []string) Map {
excluded := make(Map)
for k, v := range m {
if !contains(exclude, k) {
excluded[k] = v
}
}
return excluded
}
// Copy creates a shallow copy of the Obj.
func (m Map) Copy() Map {
copied := Map{}
for k, v := range m {
copied[k] = v
}
return copied
}
// Merge blends the specified map with a copy of this map and returns the result.
//
// Keys that appear in both will be selected from the specified map.
// This method requires that the wrapped object be a map[string]interface{}
func (m Map) Merge(merge Map) Map {
return m.Copy().MergeHere(merge)
}
// MergeHere blends the specified map with this map and returns the current map.
//
// Keys that appear in both will be selected from the specified map. The original map
// will be modified. This method requires that
// the wrapped object be a map[string]interface{}
func (m Map) MergeHere(merge Map) Map {
for k, v := range merge {
m[k] = v
}
return m
}
// Transform builds a new Obj giving the transformer a chance
// to change the keys and values as it goes. This method requires that
// the wrapped object be a map[string]interface{}
func (m Map) Transform(transformer func(key string, value interface{}) (string, interface{})) Map {
newMap := Map{}
for k, v := range m {
modifiedKey, modifiedVal := transformer(k, v)
newMap[modifiedKey] = modifiedVal
}
return newMap
}
// TransformKeys builds a new map using the specified key mapping.
//
// Unspecified keys will be unaltered.
// This method requires that the wrapped object be a map[string]interface{}
func (m Map) TransformKeys(mapping map[string]string) Map {
return m.Transform(func(key string, value interface{}) (string, interface{}) {
if newKey, ok := mapping[key]; ok {
return newKey, value
}
return key, value
})
}
// Checks if a string slice contains a string
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
objx-0.5.2/mutations_test.go 0000664 0000000 0000000 00000004052 14570052437 0016101 0 ustar 00root root 0000000 0000000 package objx_test
import (
"strings"
"testing"
"github.com/stretchr/objx"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestExclude(t *testing.T) {
m := objx.Map{
"name": "Mat",
"age": 29,
"secret": "ABC",
}
excluded := m.Exclude([]string{"secret"})
assert.Equal(t, m["name"], excluded["name"])
assert.Equal(t, m["age"], excluded["age"])
assert.False(t, excluded.Has("secret"), "secret should be excluded")
}
func TestCopy(t *testing.T) {
m1 := objx.Map{
"name": "Tyler",
"location": "UT",
}
m2 := m1.Copy()
require.NotNil(t, m2)
m2["name"] = "Mat"
assert.Equal(t, m1.Get("name").Str(), "Tyler")
assert.Equal(t, m2.Get("name").Str(), "Mat")
}
func TestMerge(t *testing.T) {
m1 := objx.Map{
"name": "Mat",
}
m2 := objx.Map{
"name": "Tyler",
"location": "UT",
}
merged := m1.Merge(m2)
assert.Equal(t, merged.Get("name").Str(), m2.Get("name").Str())
assert.Equal(t, merged.Get("location").Str(), m2.Get("location").Str())
assert.Empty(t, m1.Get("location").Str())
}
func TestMergeHere(t *testing.T) {
m1 := objx.Map{
"name": "Mat",
}
m2 := objx.Map{
"name": "Tyler",
"location": "UT",
}
merged := m1.MergeHere(m2)
assert.Equal(t, m1, merged, "With MergeHere, it should return the first modified map")
assert.Equal(t, merged.Get("name").Str(), m2.Get("name").Str())
assert.Equal(t, merged.Get("location").Str(), m2.Get("location").Str())
assert.Equal(t, merged.Get("location").Str(), m1.Get("location").Str())
}
func TestTransform(t *testing.T) {
m := objx.Map{
"name": "Mat",
"location": "UK",
}
r := m.Transform(keyToUpper)
assert.Equal(t, objx.Map{
"NAME": "Mat",
"LOCATION": "UK",
}, r)
}
func TestTransformKeys(t *testing.T) {
m := objx.Map{
"a": "1",
"b": "2",
"c": "3",
}
mapping := map[string]string{
"a": "d",
"b": "e",
}
r := m.TransformKeys(mapping)
assert.Equal(t, objx.Map{
"c": "3",
"d": "1",
"e": "2",
}, r)
}
func keyToUpper(s string, v interface{}) (string, interface{}) {
return strings.ToUpper(s), v
}
objx-0.5.2/security.go 0000664 0000000 0000000 00000000363 14570052437 0014667 0 ustar 00root root 0000000 0000000 package objx
import (
"crypto/sha1"
"encoding/hex"
)
// HashWithKey hashes the specified string using the security key
func HashWithKey(data, key string) string {
d := sha1.Sum([]byte(data + ":" + key))
return hex.EncodeToString(d[:])
}
objx-0.5.2/security_test.go 0000664 0000000 0000000 00000000361 14570052437 0015724 0 ustar 00root root 0000000 0000000 package objx_test
import (
"testing"
"github.com/stretchr/objx"
"github.com/stretchr/testify/assert"
)
func TestHashWithKey(t *testing.T) {
assert.Equal(t, "0ce84d8d01f2c7b6e0882b784429c54d280ea2d9", objx.HashWithKey("abc", "def"))
}
objx-0.5.2/simple_example_test.go 0000664 0000000 0000000 00000002146 14570052437 0017064 0 ustar 00root root 0000000 0000000 package objx_test
import (
"testing"
"github.com/stretchr/objx"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSimpleExample(t *testing.T) {
// build a map from a JSON object
o := objx.MustFromJSON(`{"name":"Mat","foods":["indian","chinese"], "location":{"county":"hobbiton","city":"the shire"}}`)
// Map can be used as a straight map[string]interface{}
assert.Equal(t, o["name"], "Mat")
// Get an Value object
v := o.Get("name")
require.NotNil(t, v)
// Test the contained value
assert.False(t, v.IsInt())
assert.False(t, v.IsBool())
assert.True(t, v.IsStr())
// Get the contained value
assert.Equal(t, v.Str(), "Mat")
// Get a default value if the contained value is not of the expected type or does not exist
assert.Equal(t, 1, v.Int(1))
// Get a value by using array notation
assert.Equal(t, "indian", o.Get("foods[0]").Data())
// Set a value by using array notation
o.Set("foods[0]", "italian")
assert.Equal(t, "italian", o.Get("foods[0]").Str())
// Get a value by using dot notation
assert.Equal(t, "hobbiton", o.Get("location.county").Str())
}
objx-0.5.2/tests.go 0000664 0000000 0000000 00000000552 14570052437 0014162 0 ustar 00root root 0000000 0000000 package objx
// Has gets whether there is something at the specified selector
// or not.
//
// If m is nil, Has will always return false.
func (m Map) Has(selector string) bool {
if m == nil {
return false
}
return !m.Get(selector).IsNil()
}
// IsNil gets whether the data is nil or not.
func (v *Value) IsNil() bool {
return v == nil || v.data == nil
}
objx-0.5.2/tests_test.go 0000664 0000000 0000000 00000000734 14570052437 0015223 0 ustar 00root root 0000000 0000000 package objx_test
import (
"testing"
"github.com/stretchr/objx"
"github.com/stretchr/testify/assert"
)
func TestHas(t *testing.T) {
m := objx.Map(TestMap)
assert.True(t, m.Has("name"))
assert.True(t, m.Has("address.state"))
assert.True(t, m.Has("numbers[4]"))
assert.False(t, m.Has("address.state.nope"))
assert.False(t, m.Has("address.nope"))
assert.False(t, m.Has("nope"))
assert.False(t, m.Has("numbers[5]"))
m = nil
assert.False(t, m.Has("nothing"))
}
objx-0.5.2/type_specific.go 0000664 0000000 0000000 00000022032 14570052437 0015643 0 ustar 00root root 0000000 0000000 package objx
/*
MSI (map[string]interface{} and []map[string]interface{})
*/
// MSI gets the value as a map[string]interface{}, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) MSI(optionalDefault ...map[string]interface{}) map[string]interface{} {
if s, ok := v.data.(map[string]interface{}); ok {
return s
}
if s, ok := v.data.(Map); ok {
return map[string]interface{}(s)
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustMSI gets the value as a map[string]interface{}.
//
// Panics if the object is not a map[string]interface{}.
func (v *Value) MustMSI() map[string]interface{} {
if s, ok := v.data.(Map); ok {
return map[string]interface{}(s)
}
return v.data.(map[string]interface{})
}
// MSISlice gets the value as a []map[string]interface{}, returns the optionalDefault
// value or nil if the value is not a []map[string]interface{}.
func (v *Value) MSISlice(optionalDefault ...[]map[string]interface{}) []map[string]interface{} {
if s, ok := v.data.([]map[string]interface{}); ok {
return s
}
s := v.ObjxMapSlice()
if s == nil {
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
result := make([]map[string]interface{}, len(s))
for i := range s {
result[i] = s[i].Value().MSI()
}
return result
}
// MustMSISlice gets the value as a []map[string]interface{}.
//
// Panics if the object is not a []map[string]interface{}.
func (v *Value) MustMSISlice() []map[string]interface{} {
if s := v.MSISlice(); s != nil {
return s
}
return v.data.([]map[string]interface{})
}
// IsMSI gets whether the object contained is a map[string]interface{} or not.
func (v *Value) IsMSI() bool {
_, ok := v.data.(map[string]interface{})
if !ok {
_, ok = v.data.(Map)
}
return ok
}
// IsMSISlice gets whether the object contained is a []map[string]interface{} or not.
func (v *Value) IsMSISlice() bool {
_, ok := v.data.([]map[string]interface{})
if !ok {
_, ok = v.data.([]Map)
if !ok {
s, ok := v.data.([]interface{})
if ok {
for i := range s {
switch s[i].(type) {
case Map:
case map[string]interface{}:
default:
return false
}
}
return true
}
}
}
return ok
}
// EachMSI calls the specified callback for each object
// in the []map[string]interface{}.
//
// Panics if the object is the wrong type.
func (v *Value) EachMSI(callback func(int, map[string]interface{}) bool) *Value {
for index, val := range v.MustMSISlice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereMSI uses the specified decider function to select items
// from the []map[string]interface{}. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereMSI(decider func(int, map[string]interface{}) bool) *Value {
var selected []map[string]interface{}
v.EachMSI(func(index int, val map[string]interface{}) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupMSI uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]map[string]interface{}.
func (v *Value) GroupMSI(grouper func(int, map[string]interface{}) string) *Value {
groups := make(map[string][]map[string]interface{})
v.EachMSI(func(index int, val map[string]interface{}) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]map[string]interface{}, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceMSI uses the specified function to replace each map[string]interface{}s
// by iterating each item. The data in the returned result will be a
// []map[string]interface{} containing the replaced items.
func (v *Value) ReplaceMSI(replacer func(int, map[string]interface{}) map[string]interface{}) *Value {
arr := v.MustMSISlice()
replaced := make([]map[string]interface{}, len(arr))
v.EachMSI(func(index int, val map[string]interface{}) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectMSI uses the specified collector function to collect a value
// for each of the map[string]interface{}s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectMSI(collector func(int, map[string]interface{}) interface{}) *Value {
arr := v.MustMSISlice()
collected := make([]interface{}, len(arr))
v.EachMSI(func(index int, val map[string]interface{}) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
ObjxMap ((Map) and [](Map))
*/
// ObjxMap gets the value as a (Map), returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) ObjxMap(optionalDefault ...(Map)) Map {
if s, ok := v.data.((Map)); ok {
return s
}
if s, ok := v.data.(map[string]interface{}); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return New(nil)
}
// MustObjxMap gets the value as a (Map).
//
// Panics if the object is not a (Map).
func (v *Value) MustObjxMap() Map {
if s, ok := v.data.(map[string]interface{}); ok {
return s
}
return v.data.((Map))
}
// ObjxMapSlice gets the value as a [](Map), returns the optionalDefault
// value or nil if the value is not a [](Map).
func (v *Value) ObjxMapSlice(optionalDefault ...[](Map)) [](Map) {
if s, ok := v.data.([]Map); ok {
return s
}
if s, ok := v.data.([]map[string]interface{}); ok {
result := make([]Map, len(s))
for i := range s {
result[i] = s[i]
}
return result
}
s, ok := v.data.([]interface{})
if !ok {
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
result := make([]Map, len(s))
for i := range s {
switch s[i].(type) {
case Map:
result[i] = s[i].(Map)
case map[string]interface{}:
result[i] = New(s[i])
default:
return nil
}
}
return result
}
// MustObjxMapSlice gets the value as a [](Map).
//
// Panics if the object is not a [](Map).
func (v *Value) MustObjxMapSlice() [](Map) {
if s := v.ObjxMapSlice(); s != nil {
return s
}
return v.data.([](Map))
}
// IsObjxMap gets whether the object contained is a (Map) or not.
func (v *Value) IsObjxMap() bool {
_, ok := v.data.((Map))
if !ok {
_, ok = v.data.(map[string]interface{})
}
return ok
}
// IsObjxMapSlice gets whether the object contained is a [](Map) or not.
func (v *Value) IsObjxMapSlice() bool {
_, ok := v.data.([](Map))
if !ok {
_, ok = v.data.([]map[string]interface{})
if !ok {
s, ok := v.data.([]interface{})
if ok {
for i := range s {
switch s[i].(type) {
case Map:
case map[string]interface{}:
default:
return false
}
}
return true
}
}
}
return ok
}
// EachObjxMap calls the specified callback for each object
// in the [](Map).
//
// Panics if the object is the wrong type.
func (v *Value) EachObjxMap(callback func(int, Map) bool) *Value {
for index, val := range v.MustObjxMapSlice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereObjxMap uses the specified decider function to select items
// from the [](Map). The object contained in the result will contain
// only the selected items.
func (v *Value) WhereObjxMap(decider func(int, Map) bool) *Value {
var selected [](Map)
v.EachObjxMap(func(index int, val Map) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupObjxMap uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][](Map).
func (v *Value) GroupObjxMap(grouper func(int, Map) string) *Value {
groups := make(map[string][](Map))
v.EachObjxMap(func(index int, val Map) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([](Map), 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceObjxMap uses the specified function to replace each (Map)s
// by iterating each item. The data in the returned result will be a
// [](Map) containing the replaced items.
func (v *Value) ReplaceObjxMap(replacer func(int, Map) Map) *Value {
arr := v.MustObjxMapSlice()
replaced := make([](Map), len(arr))
v.EachObjxMap(func(index int, val Map) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectObjxMap uses the specified collector function to collect a value
// for each of the (Map)s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectObjxMap(collector func(int, Map) interface{}) *Value {
arr := v.MustObjxMapSlice()
collected := make([]interface{}, len(arr))
v.EachObjxMap(func(index int, val Map) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
objx-0.5.2/type_specific_codegen.go 0000664 0000000 0000000 00000174262 14570052437 0017344 0 ustar 00root root 0000000 0000000 package objx
/*
Inter (interface{} and []interface{})
*/
// Inter gets the value as a interface{}, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Inter(optionalDefault ...interface{}) interface{} {
if s, ok := v.data.(interface{}); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustInter gets the value as a interface{}.
//
// Panics if the object is not a interface{}.
func (v *Value) MustInter() interface{} {
return v.data.(interface{})
}
// InterSlice gets the value as a []interface{}, returns the optionalDefault
// value or nil if the value is not a []interface{}.
func (v *Value) InterSlice(optionalDefault ...[]interface{}) []interface{} {
if s, ok := v.data.([]interface{}); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustInterSlice gets the value as a []interface{}.
//
// Panics if the object is not a []interface{}.
func (v *Value) MustInterSlice() []interface{} {
return v.data.([]interface{})
}
// IsInter gets whether the object contained is a interface{} or not.
func (v *Value) IsInter() bool {
_, ok := v.data.(interface{})
return ok
}
// IsInterSlice gets whether the object contained is a []interface{} or not.
func (v *Value) IsInterSlice() bool {
_, ok := v.data.([]interface{})
return ok
}
// EachInter calls the specified callback for each object
// in the []interface{}.
//
// Panics if the object is the wrong type.
func (v *Value) EachInter(callback func(int, interface{}) bool) *Value {
for index, val := range v.MustInterSlice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereInter uses the specified decider function to select items
// from the []interface{}. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereInter(decider func(int, interface{}) bool) *Value {
var selected []interface{}
v.EachInter(func(index int, val interface{}) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupInter uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]interface{}.
func (v *Value) GroupInter(grouper func(int, interface{}) string) *Value {
groups := make(map[string][]interface{})
v.EachInter(func(index int, val interface{}) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]interface{}, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceInter uses the specified function to replace each interface{}s
// by iterating each item. The data in the returned result will be a
// []interface{} containing the replaced items.
func (v *Value) ReplaceInter(replacer func(int, interface{}) interface{}) *Value {
arr := v.MustInterSlice()
replaced := make([]interface{}, len(arr))
v.EachInter(func(index int, val interface{}) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectInter uses the specified collector function to collect a value
// for each of the interface{}s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectInter(collector func(int, interface{}) interface{}) *Value {
arr := v.MustInterSlice()
collected := make([]interface{}, len(arr))
v.EachInter(func(index int, val interface{}) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Bool (bool and []bool)
*/
// Bool gets the value as a bool, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Bool(optionalDefault ...bool) bool {
if s, ok := v.data.(bool); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return false
}
// MustBool gets the value as a bool.
//
// Panics if the object is not a bool.
func (v *Value) MustBool() bool {
return v.data.(bool)
}
// BoolSlice gets the value as a []bool, returns the optionalDefault
// value or nil if the value is not a []bool.
func (v *Value) BoolSlice(optionalDefault ...[]bool) []bool {
if s, ok := v.data.([]bool); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustBoolSlice gets the value as a []bool.
//
// Panics if the object is not a []bool.
func (v *Value) MustBoolSlice() []bool {
return v.data.([]bool)
}
// IsBool gets whether the object contained is a bool or not.
func (v *Value) IsBool() bool {
_, ok := v.data.(bool)
return ok
}
// IsBoolSlice gets whether the object contained is a []bool or not.
func (v *Value) IsBoolSlice() bool {
_, ok := v.data.([]bool)
return ok
}
// EachBool calls the specified callback for each object
// in the []bool.
//
// Panics if the object is the wrong type.
func (v *Value) EachBool(callback func(int, bool) bool) *Value {
for index, val := range v.MustBoolSlice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereBool uses the specified decider function to select items
// from the []bool. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereBool(decider func(int, bool) bool) *Value {
var selected []bool
v.EachBool(func(index int, val bool) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupBool uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]bool.
func (v *Value) GroupBool(grouper func(int, bool) string) *Value {
groups := make(map[string][]bool)
v.EachBool(func(index int, val bool) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]bool, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceBool uses the specified function to replace each bools
// by iterating each item. The data in the returned result will be a
// []bool containing the replaced items.
func (v *Value) ReplaceBool(replacer func(int, bool) bool) *Value {
arr := v.MustBoolSlice()
replaced := make([]bool, len(arr))
v.EachBool(func(index int, val bool) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectBool uses the specified collector function to collect a value
// for each of the bools in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectBool(collector func(int, bool) interface{}) *Value {
arr := v.MustBoolSlice()
collected := make([]interface{}, len(arr))
v.EachBool(func(index int, val bool) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Str (string and []string)
*/
// Str gets the value as a string, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Str(optionalDefault ...string) string {
if s, ok := v.data.(string); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return ""
}
// MustStr gets the value as a string.
//
// Panics if the object is not a string.
func (v *Value) MustStr() string {
return v.data.(string)
}
// StrSlice gets the value as a []string, returns the optionalDefault
// value or nil if the value is not a []string.
func (v *Value) StrSlice(optionalDefault ...[]string) []string {
if s, ok := v.data.([]string); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustStrSlice gets the value as a []string.
//
// Panics if the object is not a []string.
func (v *Value) MustStrSlice() []string {
return v.data.([]string)
}
// IsStr gets whether the object contained is a string or not.
func (v *Value) IsStr() bool {
_, ok := v.data.(string)
return ok
}
// IsStrSlice gets whether the object contained is a []string or not.
func (v *Value) IsStrSlice() bool {
_, ok := v.data.([]string)
return ok
}
// EachStr calls the specified callback for each object
// in the []string.
//
// Panics if the object is the wrong type.
func (v *Value) EachStr(callback func(int, string) bool) *Value {
for index, val := range v.MustStrSlice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereStr uses the specified decider function to select items
// from the []string. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereStr(decider func(int, string) bool) *Value {
var selected []string
v.EachStr(func(index int, val string) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupStr uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]string.
func (v *Value) GroupStr(grouper func(int, string) string) *Value {
groups := make(map[string][]string)
v.EachStr(func(index int, val string) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]string, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceStr uses the specified function to replace each strings
// by iterating each item. The data in the returned result will be a
// []string containing the replaced items.
func (v *Value) ReplaceStr(replacer func(int, string) string) *Value {
arr := v.MustStrSlice()
replaced := make([]string, len(arr))
v.EachStr(func(index int, val string) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectStr uses the specified collector function to collect a value
// for each of the strings in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectStr(collector func(int, string) interface{}) *Value {
arr := v.MustStrSlice()
collected := make([]interface{}, len(arr))
v.EachStr(func(index int, val string) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Int (int and []int)
*/
// Int gets the value as a int, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Int(optionalDefault ...int) int {
if s, ok := v.data.(int); ok {
return s
}
if s, ok := v.data.(float64); ok {
if float64(int(s)) == s {
return int(s)
}
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustInt gets the value as a int.
//
// Panics if the object is not a int.
func (v *Value) MustInt() int {
if s, ok := v.data.(float64); ok {
if float64(int(s)) == s {
return int(s)
}
}
return v.data.(int)
}
// IntSlice gets the value as a []int, returns the optionalDefault
// value or nil if the value is not a []int.
func (v *Value) IntSlice(optionalDefault ...[]int) []int {
if s, ok := v.data.([]int); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustIntSlice gets the value as a []int.
//
// Panics if the object is not a []int.
func (v *Value) MustIntSlice() []int {
return v.data.([]int)
}
// IsInt gets whether the object contained is a int or not.
func (v *Value) IsInt() bool {
_, ok := v.data.(int)
return ok
}
// IsIntSlice gets whether the object contained is a []int or not.
func (v *Value) IsIntSlice() bool {
_, ok := v.data.([]int)
return ok
}
// EachInt calls the specified callback for each object
// in the []int.
//
// Panics if the object is the wrong type.
func (v *Value) EachInt(callback func(int, int) bool) *Value {
for index, val := range v.MustIntSlice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereInt uses the specified decider function to select items
// from the []int. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereInt(decider func(int, int) bool) *Value {
var selected []int
v.EachInt(func(index int, val int) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupInt uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]int.
func (v *Value) GroupInt(grouper func(int, int) string) *Value {
groups := make(map[string][]int)
v.EachInt(func(index int, val int) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]int, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceInt uses the specified function to replace each ints
// by iterating each item. The data in the returned result will be a
// []int containing the replaced items.
func (v *Value) ReplaceInt(replacer func(int, int) int) *Value {
arr := v.MustIntSlice()
replaced := make([]int, len(arr))
v.EachInt(func(index int, val int) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectInt uses the specified collector function to collect a value
// for each of the ints in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectInt(collector func(int, int) interface{}) *Value {
arr := v.MustIntSlice()
collected := make([]interface{}, len(arr))
v.EachInt(func(index int, val int) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Int8 (int8 and []int8)
*/
// Int8 gets the value as a int8, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Int8(optionalDefault ...int8) int8 {
if s, ok := v.data.(int8); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustInt8 gets the value as a int8.
//
// Panics if the object is not a int8.
func (v *Value) MustInt8() int8 {
return v.data.(int8)
}
// Int8Slice gets the value as a []int8, returns the optionalDefault
// value or nil if the value is not a []int8.
func (v *Value) Int8Slice(optionalDefault ...[]int8) []int8 {
if s, ok := v.data.([]int8); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustInt8Slice gets the value as a []int8.
//
// Panics if the object is not a []int8.
func (v *Value) MustInt8Slice() []int8 {
return v.data.([]int8)
}
// IsInt8 gets whether the object contained is a int8 or not.
func (v *Value) IsInt8() bool {
_, ok := v.data.(int8)
return ok
}
// IsInt8Slice gets whether the object contained is a []int8 or not.
func (v *Value) IsInt8Slice() bool {
_, ok := v.data.([]int8)
return ok
}
// EachInt8 calls the specified callback for each object
// in the []int8.
//
// Panics if the object is the wrong type.
func (v *Value) EachInt8(callback func(int, int8) bool) *Value {
for index, val := range v.MustInt8Slice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereInt8 uses the specified decider function to select items
// from the []int8. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereInt8(decider func(int, int8) bool) *Value {
var selected []int8
v.EachInt8(func(index int, val int8) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupInt8 uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]int8.
func (v *Value) GroupInt8(grouper func(int, int8) string) *Value {
groups := make(map[string][]int8)
v.EachInt8(func(index int, val int8) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]int8, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceInt8 uses the specified function to replace each int8s
// by iterating each item. The data in the returned result will be a
// []int8 containing the replaced items.
func (v *Value) ReplaceInt8(replacer func(int, int8) int8) *Value {
arr := v.MustInt8Slice()
replaced := make([]int8, len(arr))
v.EachInt8(func(index int, val int8) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectInt8 uses the specified collector function to collect a value
// for each of the int8s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectInt8(collector func(int, int8) interface{}) *Value {
arr := v.MustInt8Slice()
collected := make([]interface{}, len(arr))
v.EachInt8(func(index int, val int8) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Int16 (int16 and []int16)
*/
// Int16 gets the value as a int16, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Int16(optionalDefault ...int16) int16 {
if s, ok := v.data.(int16); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustInt16 gets the value as a int16.
//
// Panics if the object is not a int16.
func (v *Value) MustInt16() int16 {
return v.data.(int16)
}
// Int16Slice gets the value as a []int16, returns the optionalDefault
// value or nil if the value is not a []int16.
func (v *Value) Int16Slice(optionalDefault ...[]int16) []int16 {
if s, ok := v.data.([]int16); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustInt16Slice gets the value as a []int16.
//
// Panics if the object is not a []int16.
func (v *Value) MustInt16Slice() []int16 {
return v.data.([]int16)
}
// IsInt16 gets whether the object contained is a int16 or not.
func (v *Value) IsInt16() bool {
_, ok := v.data.(int16)
return ok
}
// IsInt16Slice gets whether the object contained is a []int16 or not.
func (v *Value) IsInt16Slice() bool {
_, ok := v.data.([]int16)
return ok
}
// EachInt16 calls the specified callback for each object
// in the []int16.
//
// Panics if the object is the wrong type.
func (v *Value) EachInt16(callback func(int, int16) bool) *Value {
for index, val := range v.MustInt16Slice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereInt16 uses the specified decider function to select items
// from the []int16. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereInt16(decider func(int, int16) bool) *Value {
var selected []int16
v.EachInt16(func(index int, val int16) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupInt16 uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]int16.
func (v *Value) GroupInt16(grouper func(int, int16) string) *Value {
groups := make(map[string][]int16)
v.EachInt16(func(index int, val int16) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]int16, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceInt16 uses the specified function to replace each int16s
// by iterating each item. The data in the returned result will be a
// []int16 containing the replaced items.
func (v *Value) ReplaceInt16(replacer func(int, int16) int16) *Value {
arr := v.MustInt16Slice()
replaced := make([]int16, len(arr))
v.EachInt16(func(index int, val int16) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectInt16 uses the specified collector function to collect a value
// for each of the int16s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectInt16(collector func(int, int16) interface{}) *Value {
arr := v.MustInt16Slice()
collected := make([]interface{}, len(arr))
v.EachInt16(func(index int, val int16) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Int32 (int32 and []int32)
*/
// Int32 gets the value as a int32, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Int32(optionalDefault ...int32) int32 {
if s, ok := v.data.(int32); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustInt32 gets the value as a int32.
//
// Panics if the object is not a int32.
func (v *Value) MustInt32() int32 {
return v.data.(int32)
}
// Int32Slice gets the value as a []int32, returns the optionalDefault
// value or nil if the value is not a []int32.
func (v *Value) Int32Slice(optionalDefault ...[]int32) []int32 {
if s, ok := v.data.([]int32); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustInt32Slice gets the value as a []int32.
//
// Panics if the object is not a []int32.
func (v *Value) MustInt32Slice() []int32 {
return v.data.([]int32)
}
// IsInt32 gets whether the object contained is a int32 or not.
func (v *Value) IsInt32() bool {
_, ok := v.data.(int32)
return ok
}
// IsInt32Slice gets whether the object contained is a []int32 or not.
func (v *Value) IsInt32Slice() bool {
_, ok := v.data.([]int32)
return ok
}
// EachInt32 calls the specified callback for each object
// in the []int32.
//
// Panics if the object is the wrong type.
func (v *Value) EachInt32(callback func(int, int32) bool) *Value {
for index, val := range v.MustInt32Slice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereInt32 uses the specified decider function to select items
// from the []int32. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereInt32(decider func(int, int32) bool) *Value {
var selected []int32
v.EachInt32(func(index int, val int32) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupInt32 uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]int32.
func (v *Value) GroupInt32(grouper func(int, int32) string) *Value {
groups := make(map[string][]int32)
v.EachInt32(func(index int, val int32) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]int32, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceInt32 uses the specified function to replace each int32s
// by iterating each item. The data in the returned result will be a
// []int32 containing the replaced items.
func (v *Value) ReplaceInt32(replacer func(int, int32) int32) *Value {
arr := v.MustInt32Slice()
replaced := make([]int32, len(arr))
v.EachInt32(func(index int, val int32) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectInt32 uses the specified collector function to collect a value
// for each of the int32s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectInt32(collector func(int, int32) interface{}) *Value {
arr := v.MustInt32Slice()
collected := make([]interface{}, len(arr))
v.EachInt32(func(index int, val int32) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Int64 (int64 and []int64)
*/
// Int64 gets the value as a int64, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Int64(optionalDefault ...int64) int64 {
if s, ok := v.data.(int64); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustInt64 gets the value as a int64.
//
// Panics if the object is not a int64.
func (v *Value) MustInt64() int64 {
return v.data.(int64)
}
// Int64Slice gets the value as a []int64, returns the optionalDefault
// value or nil if the value is not a []int64.
func (v *Value) Int64Slice(optionalDefault ...[]int64) []int64 {
if s, ok := v.data.([]int64); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustInt64Slice gets the value as a []int64.
//
// Panics if the object is not a []int64.
func (v *Value) MustInt64Slice() []int64 {
return v.data.([]int64)
}
// IsInt64 gets whether the object contained is a int64 or not.
func (v *Value) IsInt64() bool {
_, ok := v.data.(int64)
return ok
}
// IsInt64Slice gets whether the object contained is a []int64 or not.
func (v *Value) IsInt64Slice() bool {
_, ok := v.data.([]int64)
return ok
}
// EachInt64 calls the specified callback for each object
// in the []int64.
//
// Panics if the object is the wrong type.
func (v *Value) EachInt64(callback func(int, int64) bool) *Value {
for index, val := range v.MustInt64Slice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereInt64 uses the specified decider function to select items
// from the []int64. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereInt64(decider func(int, int64) bool) *Value {
var selected []int64
v.EachInt64(func(index int, val int64) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupInt64 uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]int64.
func (v *Value) GroupInt64(grouper func(int, int64) string) *Value {
groups := make(map[string][]int64)
v.EachInt64(func(index int, val int64) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]int64, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceInt64 uses the specified function to replace each int64s
// by iterating each item. The data in the returned result will be a
// []int64 containing the replaced items.
func (v *Value) ReplaceInt64(replacer func(int, int64) int64) *Value {
arr := v.MustInt64Slice()
replaced := make([]int64, len(arr))
v.EachInt64(func(index int, val int64) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectInt64 uses the specified collector function to collect a value
// for each of the int64s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectInt64(collector func(int, int64) interface{}) *Value {
arr := v.MustInt64Slice()
collected := make([]interface{}, len(arr))
v.EachInt64(func(index int, val int64) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Uint (uint and []uint)
*/
// Uint gets the value as a uint, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Uint(optionalDefault ...uint) uint {
if s, ok := v.data.(uint); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustUint gets the value as a uint.
//
// Panics if the object is not a uint.
func (v *Value) MustUint() uint {
return v.data.(uint)
}
// UintSlice gets the value as a []uint, returns the optionalDefault
// value or nil if the value is not a []uint.
func (v *Value) UintSlice(optionalDefault ...[]uint) []uint {
if s, ok := v.data.([]uint); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustUintSlice gets the value as a []uint.
//
// Panics if the object is not a []uint.
func (v *Value) MustUintSlice() []uint {
return v.data.([]uint)
}
// IsUint gets whether the object contained is a uint or not.
func (v *Value) IsUint() bool {
_, ok := v.data.(uint)
return ok
}
// IsUintSlice gets whether the object contained is a []uint or not.
func (v *Value) IsUintSlice() bool {
_, ok := v.data.([]uint)
return ok
}
// EachUint calls the specified callback for each object
// in the []uint.
//
// Panics if the object is the wrong type.
func (v *Value) EachUint(callback func(int, uint) bool) *Value {
for index, val := range v.MustUintSlice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereUint uses the specified decider function to select items
// from the []uint. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereUint(decider func(int, uint) bool) *Value {
var selected []uint
v.EachUint(func(index int, val uint) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupUint uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]uint.
func (v *Value) GroupUint(grouper func(int, uint) string) *Value {
groups := make(map[string][]uint)
v.EachUint(func(index int, val uint) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]uint, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceUint uses the specified function to replace each uints
// by iterating each item. The data in the returned result will be a
// []uint containing the replaced items.
func (v *Value) ReplaceUint(replacer func(int, uint) uint) *Value {
arr := v.MustUintSlice()
replaced := make([]uint, len(arr))
v.EachUint(func(index int, val uint) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectUint uses the specified collector function to collect a value
// for each of the uints in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectUint(collector func(int, uint) interface{}) *Value {
arr := v.MustUintSlice()
collected := make([]interface{}, len(arr))
v.EachUint(func(index int, val uint) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Uint8 (uint8 and []uint8)
*/
// Uint8 gets the value as a uint8, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Uint8(optionalDefault ...uint8) uint8 {
if s, ok := v.data.(uint8); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustUint8 gets the value as a uint8.
//
// Panics if the object is not a uint8.
func (v *Value) MustUint8() uint8 {
return v.data.(uint8)
}
// Uint8Slice gets the value as a []uint8, returns the optionalDefault
// value or nil if the value is not a []uint8.
func (v *Value) Uint8Slice(optionalDefault ...[]uint8) []uint8 {
if s, ok := v.data.([]uint8); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustUint8Slice gets the value as a []uint8.
//
// Panics if the object is not a []uint8.
func (v *Value) MustUint8Slice() []uint8 {
return v.data.([]uint8)
}
// IsUint8 gets whether the object contained is a uint8 or not.
func (v *Value) IsUint8() bool {
_, ok := v.data.(uint8)
return ok
}
// IsUint8Slice gets whether the object contained is a []uint8 or not.
func (v *Value) IsUint8Slice() bool {
_, ok := v.data.([]uint8)
return ok
}
// EachUint8 calls the specified callback for each object
// in the []uint8.
//
// Panics if the object is the wrong type.
func (v *Value) EachUint8(callback func(int, uint8) bool) *Value {
for index, val := range v.MustUint8Slice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereUint8 uses the specified decider function to select items
// from the []uint8. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereUint8(decider func(int, uint8) bool) *Value {
var selected []uint8
v.EachUint8(func(index int, val uint8) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupUint8 uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]uint8.
func (v *Value) GroupUint8(grouper func(int, uint8) string) *Value {
groups := make(map[string][]uint8)
v.EachUint8(func(index int, val uint8) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]uint8, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceUint8 uses the specified function to replace each uint8s
// by iterating each item. The data in the returned result will be a
// []uint8 containing the replaced items.
func (v *Value) ReplaceUint8(replacer func(int, uint8) uint8) *Value {
arr := v.MustUint8Slice()
replaced := make([]uint8, len(arr))
v.EachUint8(func(index int, val uint8) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectUint8 uses the specified collector function to collect a value
// for each of the uint8s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectUint8(collector func(int, uint8) interface{}) *Value {
arr := v.MustUint8Slice()
collected := make([]interface{}, len(arr))
v.EachUint8(func(index int, val uint8) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Uint16 (uint16 and []uint16)
*/
// Uint16 gets the value as a uint16, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Uint16(optionalDefault ...uint16) uint16 {
if s, ok := v.data.(uint16); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustUint16 gets the value as a uint16.
//
// Panics if the object is not a uint16.
func (v *Value) MustUint16() uint16 {
return v.data.(uint16)
}
// Uint16Slice gets the value as a []uint16, returns the optionalDefault
// value or nil if the value is not a []uint16.
func (v *Value) Uint16Slice(optionalDefault ...[]uint16) []uint16 {
if s, ok := v.data.([]uint16); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustUint16Slice gets the value as a []uint16.
//
// Panics if the object is not a []uint16.
func (v *Value) MustUint16Slice() []uint16 {
return v.data.([]uint16)
}
// IsUint16 gets whether the object contained is a uint16 or not.
func (v *Value) IsUint16() bool {
_, ok := v.data.(uint16)
return ok
}
// IsUint16Slice gets whether the object contained is a []uint16 or not.
func (v *Value) IsUint16Slice() bool {
_, ok := v.data.([]uint16)
return ok
}
// EachUint16 calls the specified callback for each object
// in the []uint16.
//
// Panics if the object is the wrong type.
func (v *Value) EachUint16(callback func(int, uint16) bool) *Value {
for index, val := range v.MustUint16Slice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereUint16 uses the specified decider function to select items
// from the []uint16. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereUint16(decider func(int, uint16) bool) *Value {
var selected []uint16
v.EachUint16(func(index int, val uint16) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupUint16 uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]uint16.
func (v *Value) GroupUint16(grouper func(int, uint16) string) *Value {
groups := make(map[string][]uint16)
v.EachUint16(func(index int, val uint16) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]uint16, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceUint16 uses the specified function to replace each uint16s
// by iterating each item. The data in the returned result will be a
// []uint16 containing the replaced items.
func (v *Value) ReplaceUint16(replacer func(int, uint16) uint16) *Value {
arr := v.MustUint16Slice()
replaced := make([]uint16, len(arr))
v.EachUint16(func(index int, val uint16) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectUint16 uses the specified collector function to collect a value
// for each of the uint16s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectUint16(collector func(int, uint16) interface{}) *Value {
arr := v.MustUint16Slice()
collected := make([]interface{}, len(arr))
v.EachUint16(func(index int, val uint16) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Uint32 (uint32 and []uint32)
*/
// Uint32 gets the value as a uint32, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Uint32(optionalDefault ...uint32) uint32 {
if s, ok := v.data.(uint32); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustUint32 gets the value as a uint32.
//
// Panics if the object is not a uint32.
func (v *Value) MustUint32() uint32 {
return v.data.(uint32)
}
// Uint32Slice gets the value as a []uint32, returns the optionalDefault
// value or nil if the value is not a []uint32.
func (v *Value) Uint32Slice(optionalDefault ...[]uint32) []uint32 {
if s, ok := v.data.([]uint32); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustUint32Slice gets the value as a []uint32.
//
// Panics if the object is not a []uint32.
func (v *Value) MustUint32Slice() []uint32 {
return v.data.([]uint32)
}
// IsUint32 gets whether the object contained is a uint32 or not.
func (v *Value) IsUint32() bool {
_, ok := v.data.(uint32)
return ok
}
// IsUint32Slice gets whether the object contained is a []uint32 or not.
func (v *Value) IsUint32Slice() bool {
_, ok := v.data.([]uint32)
return ok
}
// EachUint32 calls the specified callback for each object
// in the []uint32.
//
// Panics if the object is the wrong type.
func (v *Value) EachUint32(callback func(int, uint32) bool) *Value {
for index, val := range v.MustUint32Slice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereUint32 uses the specified decider function to select items
// from the []uint32. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereUint32(decider func(int, uint32) bool) *Value {
var selected []uint32
v.EachUint32(func(index int, val uint32) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupUint32 uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]uint32.
func (v *Value) GroupUint32(grouper func(int, uint32) string) *Value {
groups := make(map[string][]uint32)
v.EachUint32(func(index int, val uint32) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]uint32, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceUint32 uses the specified function to replace each uint32s
// by iterating each item. The data in the returned result will be a
// []uint32 containing the replaced items.
func (v *Value) ReplaceUint32(replacer func(int, uint32) uint32) *Value {
arr := v.MustUint32Slice()
replaced := make([]uint32, len(arr))
v.EachUint32(func(index int, val uint32) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectUint32 uses the specified collector function to collect a value
// for each of the uint32s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectUint32(collector func(int, uint32) interface{}) *Value {
arr := v.MustUint32Slice()
collected := make([]interface{}, len(arr))
v.EachUint32(func(index int, val uint32) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Uint64 (uint64 and []uint64)
*/
// Uint64 gets the value as a uint64, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Uint64(optionalDefault ...uint64) uint64 {
if s, ok := v.data.(uint64); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustUint64 gets the value as a uint64.
//
// Panics if the object is not a uint64.
func (v *Value) MustUint64() uint64 {
return v.data.(uint64)
}
// Uint64Slice gets the value as a []uint64, returns the optionalDefault
// value or nil if the value is not a []uint64.
func (v *Value) Uint64Slice(optionalDefault ...[]uint64) []uint64 {
if s, ok := v.data.([]uint64); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustUint64Slice gets the value as a []uint64.
//
// Panics if the object is not a []uint64.
func (v *Value) MustUint64Slice() []uint64 {
return v.data.([]uint64)
}
// IsUint64 gets whether the object contained is a uint64 or not.
func (v *Value) IsUint64() bool {
_, ok := v.data.(uint64)
return ok
}
// IsUint64Slice gets whether the object contained is a []uint64 or not.
func (v *Value) IsUint64Slice() bool {
_, ok := v.data.([]uint64)
return ok
}
// EachUint64 calls the specified callback for each object
// in the []uint64.
//
// Panics if the object is the wrong type.
func (v *Value) EachUint64(callback func(int, uint64) bool) *Value {
for index, val := range v.MustUint64Slice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereUint64 uses the specified decider function to select items
// from the []uint64. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereUint64(decider func(int, uint64) bool) *Value {
var selected []uint64
v.EachUint64(func(index int, val uint64) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupUint64 uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]uint64.
func (v *Value) GroupUint64(grouper func(int, uint64) string) *Value {
groups := make(map[string][]uint64)
v.EachUint64(func(index int, val uint64) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]uint64, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceUint64 uses the specified function to replace each uint64s
// by iterating each item. The data in the returned result will be a
// []uint64 containing the replaced items.
func (v *Value) ReplaceUint64(replacer func(int, uint64) uint64) *Value {
arr := v.MustUint64Slice()
replaced := make([]uint64, len(arr))
v.EachUint64(func(index int, val uint64) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectUint64 uses the specified collector function to collect a value
// for each of the uint64s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectUint64(collector func(int, uint64) interface{}) *Value {
arr := v.MustUint64Slice()
collected := make([]interface{}, len(arr))
v.EachUint64(func(index int, val uint64) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Uintptr (uintptr and []uintptr)
*/
// Uintptr gets the value as a uintptr, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Uintptr(optionalDefault ...uintptr) uintptr {
if s, ok := v.data.(uintptr); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustUintptr gets the value as a uintptr.
//
// Panics if the object is not a uintptr.
func (v *Value) MustUintptr() uintptr {
return v.data.(uintptr)
}
// UintptrSlice gets the value as a []uintptr, returns the optionalDefault
// value or nil if the value is not a []uintptr.
func (v *Value) UintptrSlice(optionalDefault ...[]uintptr) []uintptr {
if s, ok := v.data.([]uintptr); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustUintptrSlice gets the value as a []uintptr.
//
// Panics if the object is not a []uintptr.
func (v *Value) MustUintptrSlice() []uintptr {
return v.data.([]uintptr)
}
// IsUintptr gets whether the object contained is a uintptr or not.
func (v *Value) IsUintptr() bool {
_, ok := v.data.(uintptr)
return ok
}
// IsUintptrSlice gets whether the object contained is a []uintptr or not.
func (v *Value) IsUintptrSlice() bool {
_, ok := v.data.([]uintptr)
return ok
}
// EachUintptr calls the specified callback for each object
// in the []uintptr.
//
// Panics if the object is the wrong type.
func (v *Value) EachUintptr(callback func(int, uintptr) bool) *Value {
for index, val := range v.MustUintptrSlice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereUintptr uses the specified decider function to select items
// from the []uintptr. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereUintptr(decider func(int, uintptr) bool) *Value {
var selected []uintptr
v.EachUintptr(func(index int, val uintptr) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupUintptr uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]uintptr.
func (v *Value) GroupUintptr(grouper func(int, uintptr) string) *Value {
groups := make(map[string][]uintptr)
v.EachUintptr(func(index int, val uintptr) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]uintptr, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceUintptr uses the specified function to replace each uintptrs
// by iterating each item. The data in the returned result will be a
// []uintptr containing the replaced items.
func (v *Value) ReplaceUintptr(replacer func(int, uintptr) uintptr) *Value {
arr := v.MustUintptrSlice()
replaced := make([]uintptr, len(arr))
v.EachUintptr(func(index int, val uintptr) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectUintptr uses the specified collector function to collect a value
// for each of the uintptrs in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectUintptr(collector func(int, uintptr) interface{}) *Value {
arr := v.MustUintptrSlice()
collected := make([]interface{}, len(arr))
v.EachUintptr(func(index int, val uintptr) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Float32 (float32 and []float32)
*/
// Float32 gets the value as a float32, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Float32(optionalDefault ...float32) float32 {
if s, ok := v.data.(float32); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustFloat32 gets the value as a float32.
//
// Panics if the object is not a float32.
func (v *Value) MustFloat32() float32 {
return v.data.(float32)
}
// Float32Slice gets the value as a []float32, returns the optionalDefault
// value or nil if the value is not a []float32.
func (v *Value) Float32Slice(optionalDefault ...[]float32) []float32 {
if s, ok := v.data.([]float32); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustFloat32Slice gets the value as a []float32.
//
// Panics if the object is not a []float32.
func (v *Value) MustFloat32Slice() []float32 {
return v.data.([]float32)
}
// IsFloat32 gets whether the object contained is a float32 or not.
func (v *Value) IsFloat32() bool {
_, ok := v.data.(float32)
return ok
}
// IsFloat32Slice gets whether the object contained is a []float32 or not.
func (v *Value) IsFloat32Slice() bool {
_, ok := v.data.([]float32)
return ok
}
// EachFloat32 calls the specified callback for each object
// in the []float32.
//
// Panics if the object is the wrong type.
func (v *Value) EachFloat32(callback func(int, float32) bool) *Value {
for index, val := range v.MustFloat32Slice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereFloat32 uses the specified decider function to select items
// from the []float32. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereFloat32(decider func(int, float32) bool) *Value {
var selected []float32
v.EachFloat32(func(index int, val float32) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupFloat32 uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]float32.
func (v *Value) GroupFloat32(grouper func(int, float32) string) *Value {
groups := make(map[string][]float32)
v.EachFloat32(func(index int, val float32) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]float32, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceFloat32 uses the specified function to replace each float32s
// by iterating each item. The data in the returned result will be a
// []float32 containing the replaced items.
func (v *Value) ReplaceFloat32(replacer func(int, float32) float32) *Value {
arr := v.MustFloat32Slice()
replaced := make([]float32, len(arr))
v.EachFloat32(func(index int, val float32) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectFloat32 uses the specified collector function to collect a value
// for each of the float32s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectFloat32(collector func(int, float32) interface{}) *Value {
arr := v.MustFloat32Slice()
collected := make([]interface{}, len(arr))
v.EachFloat32(func(index int, val float32) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Float64 (float64 and []float64)
*/
// Float64 gets the value as a float64, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Float64(optionalDefault ...float64) float64 {
if s, ok := v.data.(float64); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustFloat64 gets the value as a float64.
//
// Panics if the object is not a float64.
func (v *Value) MustFloat64() float64 {
return v.data.(float64)
}
// Float64Slice gets the value as a []float64, returns the optionalDefault
// value or nil if the value is not a []float64.
func (v *Value) Float64Slice(optionalDefault ...[]float64) []float64 {
if s, ok := v.data.([]float64); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustFloat64Slice gets the value as a []float64.
//
// Panics if the object is not a []float64.
func (v *Value) MustFloat64Slice() []float64 {
return v.data.([]float64)
}
// IsFloat64 gets whether the object contained is a float64 or not.
func (v *Value) IsFloat64() bool {
_, ok := v.data.(float64)
return ok
}
// IsFloat64Slice gets whether the object contained is a []float64 or not.
func (v *Value) IsFloat64Slice() bool {
_, ok := v.data.([]float64)
return ok
}
// EachFloat64 calls the specified callback for each object
// in the []float64.
//
// Panics if the object is the wrong type.
func (v *Value) EachFloat64(callback func(int, float64) bool) *Value {
for index, val := range v.MustFloat64Slice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereFloat64 uses the specified decider function to select items
// from the []float64. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereFloat64(decider func(int, float64) bool) *Value {
var selected []float64
v.EachFloat64(func(index int, val float64) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupFloat64 uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]float64.
func (v *Value) GroupFloat64(grouper func(int, float64) string) *Value {
groups := make(map[string][]float64)
v.EachFloat64(func(index int, val float64) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]float64, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceFloat64 uses the specified function to replace each float64s
// by iterating each item. The data in the returned result will be a
// []float64 containing the replaced items.
func (v *Value) ReplaceFloat64(replacer func(int, float64) float64) *Value {
arr := v.MustFloat64Slice()
replaced := make([]float64, len(arr))
v.EachFloat64(func(index int, val float64) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectFloat64 uses the specified collector function to collect a value
// for each of the float64s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectFloat64(collector func(int, float64) interface{}) *Value {
arr := v.MustFloat64Slice()
collected := make([]interface{}, len(arr))
v.EachFloat64(func(index int, val float64) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Complex64 (complex64 and []complex64)
*/
// Complex64 gets the value as a complex64, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Complex64(optionalDefault ...complex64) complex64 {
if s, ok := v.data.(complex64); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustComplex64 gets the value as a complex64.
//
// Panics if the object is not a complex64.
func (v *Value) MustComplex64() complex64 {
return v.data.(complex64)
}
// Complex64Slice gets the value as a []complex64, returns the optionalDefault
// value or nil if the value is not a []complex64.
func (v *Value) Complex64Slice(optionalDefault ...[]complex64) []complex64 {
if s, ok := v.data.([]complex64); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustComplex64Slice gets the value as a []complex64.
//
// Panics if the object is not a []complex64.
func (v *Value) MustComplex64Slice() []complex64 {
return v.data.([]complex64)
}
// IsComplex64 gets whether the object contained is a complex64 or not.
func (v *Value) IsComplex64() bool {
_, ok := v.data.(complex64)
return ok
}
// IsComplex64Slice gets whether the object contained is a []complex64 or not.
func (v *Value) IsComplex64Slice() bool {
_, ok := v.data.([]complex64)
return ok
}
// EachComplex64 calls the specified callback for each object
// in the []complex64.
//
// Panics if the object is the wrong type.
func (v *Value) EachComplex64(callback func(int, complex64) bool) *Value {
for index, val := range v.MustComplex64Slice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereComplex64 uses the specified decider function to select items
// from the []complex64. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereComplex64(decider func(int, complex64) bool) *Value {
var selected []complex64
v.EachComplex64(func(index int, val complex64) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupComplex64 uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]complex64.
func (v *Value) GroupComplex64(grouper func(int, complex64) string) *Value {
groups := make(map[string][]complex64)
v.EachComplex64(func(index int, val complex64) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]complex64, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceComplex64 uses the specified function to replace each complex64s
// by iterating each item. The data in the returned result will be a
// []complex64 containing the replaced items.
func (v *Value) ReplaceComplex64(replacer func(int, complex64) complex64) *Value {
arr := v.MustComplex64Slice()
replaced := make([]complex64, len(arr))
v.EachComplex64(func(index int, val complex64) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectComplex64 uses the specified collector function to collect a value
// for each of the complex64s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectComplex64(collector func(int, complex64) interface{}) *Value {
arr := v.MustComplex64Slice()
collected := make([]interface{}, len(arr))
v.EachComplex64(func(index int, val complex64) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
/*
Complex128 (complex128 and []complex128)
*/
// Complex128 gets the value as a complex128, returns the optionalDefault
// value or a system default object if the value is the wrong type.
func (v *Value) Complex128(optionalDefault ...complex128) complex128 {
if s, ok := v.data.(complex128); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return 0
}
// MustComplex128 gets the value as a complex128.
//
// Panics if the object is not a complex128.
func (v *Value) MustComplex128() complex128 {
return v.data.(complex128)
}
// Complex128Slice gets the value as a []complex128, returns the optionalDefault
// value or nil if the value is not a []complex128.
func (v *Value) Complex128Slice(optionalDefault ...[]complex128) []complex128 {
if s, ok := v.data.([]complex128); ok {
return s
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return nil
}
// MustComplex128Slice gets the value as a []complex128.
//
// Panics if the object is not a []complex128.
func (v *Value) MustComplex128Slice() []complex128 {
return v.data.([]complex128)
}
// IsComplex128 gets whether the object contained is a complex128 or not.
func (v *Value) IsComplex128() bool {
_, ok := v.data.(complex128)
return ok
}
// IsComplex128Slice gets whether the object contained is a []complex128 or not.
func (v *Value) IsComplex128Slice() bool {
_, ok := v.data.([]complex128)
return ok
}
// EachComplex128 calls the specified callback for each object
// in the []complex128.
//
// Panics if the object is the wrong type.
func (v *Value) EachComplex128(callback func(int, complex128) bool) *Value {
for index, val := range v.MustComplex128Slice() {
carryon := callback(index, val)
if !carryon {
break
}
}
return v
}
// WhereComplex128 uses the specified decider function to select items
// from the []complex128. The object contained in the result will contain
// only the selected items.
func (v *Value) WhereComplex128(decider func(int, complex128) bool) *Value {
var selected []complex128
v.EachComplex128(func(index int, val complex128) bool {
shouldSelect := decider(index, val)
if !shouldSelect {
selected = append(selected, val)
}
return true
})
return &Value{data: selected}
}
// GroupComplex128 uses the specified grouper function to group the items
// keyed by the return of the grouper. The object contained in the
// result will contain a map[string][]complex128.
func (v *Value) GroupComplex128(grouper func(int, complex128) string) *Value {
groups := make(map[string][]complex128)
v.EachComplex128(func(index int, val complex128) bool {
group := grouper(index, val)
if _, ok := groups[group]; !ok {
groups[group] = make([]complex128, 0)
}
groups[group] = append(groups[group], val)
return true
})
return &Value{data: groups}
}
// ReplaceComplex128 uses the specified function to replace each complex128s
// by iterating each item. The data in the returned result will be a
// []complex128 containing the replaced items.
func (v *Value) ReplaceComplex128(replacer func(int, complex128) complex128) *Value {
arr := v.MustComplex128Slice()
replaced := make([]complex128, len(arr))
v.EachComplex128(func(index int, val complex128) bool {
replaced[index] = replacer(index, val)
return true
})
return &Value{data: replaced}
}
// CollectComplex128 uses the specified collector function to collect a value
// for each of the complex128s in the slice. The data returned will be a
// []interface{}.
func (v *Value) CollectComplex128(collector func(int, complex128) interface{}) *Value {
arr := v.MustComplex128Slice()
collected := make([]interface{}, len(arr))
v.EachComplex128(func(index int, val complex128) bool {
collected[index] = collector(index, val)
return true
})
return &Value{data: collected}
}
objx-0.5.2/type_specific_codegen_test.go 0000664 0000000 0000000 00000201166 14570052437 0020375 0 ustar 00root root 0000000 0000000 package objx_test
import (
"fmt"
"testing"
"github.com/stretchr/objx"
"github.com/stretchr/testify/assert"
)
/*
Tests for Inter (interface{} and []interface{})
*/
func TestInter(t *testing.T) {
val := interface{}("something")
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Inter())
assert.Equal(t, val, m.Get("value").MustInter())
assert.Equal(t, interface{}(nil), m.Get("nothing").Inter())
assert.Equal(t, val, m.Get("nothing").Inter("something"))
assert.Panics(t, func() {
m.Get("age").MustInter()
})
}
func TestInterSlice(t *testing.T) {
val := interface{}("something")
m := objx.Map{"value": []interface{}{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").InterSlice()[0])
assert.Equal(t, val, m.Get("value").MustInterSlice()[0])
assert.Equal(t, []interface{}(nil), m.Get("nothing").InterSlice())
assert.Equal(t, val, m.Get("nothing").InterSlice([]interface{}{interface{}("something")})[0])
assert.Panics(t, func() {
m.Get("nothing").MustInterSlice()
})
}
func TestIsInter(t *testing.T) {
m := objx.Map{"data": interface{}("something")}
assert.True(t, m.Get("data").IsInter())
}
func TestIsInterSlice(t *testing.T) {
m := objx.Map{"data": []interface{}{interface{}("something")}}
assert.True(t, m.Get("data").IsInterSlice())
}
func TestEachInter(t *testing.T) {
m := objx.Map{"data": []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}}
count := 0
replacedVals := make([]interface{}, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachInter(func(i int, val interface{}) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustInterSlice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustInterSlice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustInterSlice()[2])
}
func TestWhereInter(t *testing.T) {
m := objx.Map{"data": []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}}
selected := m.Get("data").WhereInter(func(i int, val interface{}) bool {
return i%2 == 0
}).MustInterSlice()
assert.Equal(t, 3, len(selected))
}
func TestGroupInter(t *testing.T) {
m := objx.Map{"data": []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}}
grouped := m.Get("data").GroupInter(func(i int, val interface{}) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]interface{})
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceInter(t *testing.T) {
m := objx.Map{"data": []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}}
rawArr := m.Get("data").MustInterSlice()
replaced := m.Get("data").ReplaceInter(func(index int, val interface{}) interface{} {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustInterSlice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectInter(t *testing.T) {
m := objx.Map{"data": []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}}
collected := m.Get("data").CollectInter(func(index int, val interface{}) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Bool (bool and []bool)
*/
func TestBool(t *testing.T) {
val := bool(true)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Bool())
assert.Equal(t, val, m.Get("value").MustBool())
assert.Equal(t, bool(false), m.Get("nothing").Bool())
assert.Equal(t, val, m.Get("nothing").Bool(true))
assert.Panics(t, func() {
m.Get("age").MustBool()
})
}
func TestBoolSlice(t *testing.T) {
val := bool(true)
m := objx.Map{"value": []bool{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").BoolSlice()[0])
assert.Equal(t, val, m.Get("value").MustBoolSlice()[0])
assert.Equal(t, []bool(nil), m.Get("nothing").BoolSlice())
assert.Equal(t, val, m.Get("nothing").BoolSlice([]bool{bool(true)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustBoolSlice()
})
}
func TestIsBool(t *testing.T) {
m := objx.Map{"data": bool(true)}
assert.True(t, m.Get("data").IsBool())
}
func TestIsBoolSlice(t *testing.T) {
m := objx.Map{"data": []bool{bool(true)}}
assert.True(t, m.Get("data").IsBoolSlice())
}
func TestEachBool(t *testing.T) {
m := objx.Map{"data": []bool{bool(true), bool(true), bool(true), bool(true), bool(true)}}
count := 0
replacedVals := make([]bool, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachBool(func(i int, val bool) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustBoolSlice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustBoolSlice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustBoolSlice()[2])
}
func TestWhereBool(t *testing.T) {
m := objx.Map{"data": []bool{bool(true), bool(true), bool(true), bool(true), bool(true), bool(true)}}
selected := m.Get("data").WhereBool(func(i int, val bool) bool {
return i%2 == 0
}).MustBoolSlice()
assert.Equal(t, 3, len(selected))
}
func TestGroupBool(t *testing.T) {
m := objx.Map{"data": []bool{bool(true), bool(true), bool(true), bool(true), bool(true), bool(true)}}
grouped := m.Get("data").GroupBool(func(i int, val bool) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]bool)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceBool(t *testing.T) {
m := objx.Map{"data": []bool{bool(true), bool(true), bool(true), bool(true), bool(true), bool(true)}}
rawArr := m.Get("data").MustBoolSlice()
replaced := m.Get("data").ReplaceBool(func(index int, val bool) bool {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustBoolSlice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectBool(t *testing.T) {
m := objx.Map{"data": []bool{bool(true), bool(true), bool(true), bool(true), bool(true), bool(true)}}
collected := m.Get("data").CollectBool(func(index int, val bool) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Str (string and []string)
*/
func TestStr(t *testing.T) {
val := string("hello")
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Str())
assert.Equal(t, val, m.Get("value").MustStr())
assert.Equal(t, string(""), m.Get("nothing").Str())
assert.Equal(t, val, m.Get("nothing").Str("hello"))
assert.Panics(t, func() {
m.Get("age").MustStr()
})
}
func TestStrSlice(t *testing.T) {
val := string("hello")
m := objx.Map{"value": []string{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").StrSlice()[0])
assert.Equal(t, val, m.Get("value").MustStrSlice()[0])
assert.Equal(t, []string(nil), m.Get("nothing").StrSlice())
assert.Equal(t, val, m.Get("nothing").StrSlice([]string{string("hello")})[0])
assert.Panics(t, func() {
m.Get("nothing").MustStrSlice()
})
}
func TestIsStr(t *testing.T) {
m := objx.Map{"data": string("hello")}
assert.True(t, m.Get("data").IsStr())
}
func TestIsStrSlice(t *testing.T) {
m := objx.Map{"data": []string{string("hello")}}
assert.True(t, m.Get("data").IsStrSlice())
}
func TestEachStr(t *testing.T) {
m := objx.Map{"data": []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}}
count := 0
replacedVals := make([]string, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachStr(func(i int, val string) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustStrSlice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustStrSlice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustStrSlice()[2])
}
func TestWhereStr(t *testing.T) {
m := objx.Map{"data": []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}}
selected := m.Get("data").WhereStr(func(i int, val string) bool {
return i%2 == 0
}).MustStrSlice()
assert.Equal(t, 3, len(selected))
}
func TestGroupStr(t *testing.T) {
m := objx.Map{"data": []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}}
grouped := m.Get("data").GroupStr(func(i int, val string) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]string)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceStr(t *testing.T) {
m := objx.Map{"data": []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}}
rawArr := m.Get("data").MustStrSlice()
replaced := m.Get("data").ReplaceStr(func(index int, val string) string {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustStrSlice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectStr(t *testing.T) {
m := objx.Map{"data": []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}}
collected := m.Get("data").CollectStr(func(index int, val string) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Int (int and []int)
*/
func TestInt(t *testing.T) {
val := int(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Int())
assert.Equal(t, val, m.Get("value").MustInt())
assert.Equal(t, int(0), m.Get("nothing").Int())
assert.Equal(t, val, m.Get("nothing").Int(1))
assert.Panics(t, func() {
m.Get("age").MustInt()
})
}
func TestIntSlice(t *testing.T) {
val := int(1)
m := objx.Map{"value": []int{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").IntSlice()[0])
assert.Equal(t, val, m.Get("value").MustIntSlice()[0])
assert.Equal(t, []int(nil), m.Get("nothing").IntSlice())
assert.Equal(t, val, m.Get("nothing").IntSlice([]int{int(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustIntSlice()
})
}
func TestIsInt(t *testing.T) {
m := objx.Map{"data": int(1)}
assert.True(t, m.Get("data").IsInt())
}
func TestIsIntSlice(t *testing.T) {
m := objx.Map{"data": []int{int(1)}}
assert.True(t, m.Get("data").IsIntSlice())
}
func TestEachInt(t *testing.T) {
m := objx.Map{"data": []int{int(1), int(1), int(1), int(1), int(1)}}
count := 0
replacedVals := make([]int, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachInt(func(i int, val int) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustIntSlice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustIntSlice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustIntSlice()[2])
}
func TestWhereInt(t *testing.T) {
m := objx.Map{"data": []int{int(1), int(1), int(1), int(1), int(1), int(1)}}
selected := m.Get("data").WhereInt(func(i int, val int) bool {
return i%2 == 0
}).MustIntSlice()
assert.Equal(t, 3, len(selected))
}
func TestGroupInt(t *testing.T) {
m := objx.Map{"data": []int{int(1), int(1), int(1), int(1), int(1), int(1)}}
grouped := m.Get("data").GroupInt(func(i int, val int) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]int)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceInt(t *testing.T) {
m := objx.Map{"data": []int{int(1), int(1), int(1), int(1), int(1), int(1)}}
rawArr := m.Get("data").MustIntSlice()
replaced := m.Get("data").ReplaceInt(func(index int, val int) int {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustIntSlice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectInt(t *testing.T) {
m := objx.Map{"data": []int{int(1), int(1), int(1), int(1), int(1), int(1)}}
collected := m.Get("data").CollectInt(func(index int, val int) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Int8 (int8 and []int8)
*/
func TestInt8(t *testing.T) {
val := int8(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Int8())
assert.Equal(t, val, m.Get("value").MustInt8())
assert.Equal(t, int8(0), m.Get("nothing").Int8())
assert.Equal(t, val, m.Get("nothing").Int8(1))
assert.Panics(t, func() {
m.Get("age").MustInt8()
})
}
func TestInt8Slice(t *testing.T) {
val := int8(1)
m := objx.Map{"value": []int8{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").Int8Slice()[0])
assert.Equal(t, val, m.Get("value").MustInt8Slice()[0])
assert.Equal(t, []int8(nil), m.Get("nothing").Int8Slice())
assert.Equal(t, val, m.Get("nothing").Int8Slice([]int8{int8(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustInt8Slice()
})
}
func TestIsInt8(t *testing.T) {
m := objx.Map{"data": int8(1)}
assert.True(t, m.Get("data").IsInt8())
}
func TestIsInt8Slice(t *testing.T) {
m := objx.Map{"data": []int8{int8(1)}}
assert.True(t, m.Get("data").IsInt8Slice())
}
func TestEachInt8(t *testing.T) {
m := objx.Map{"data": []int8{int8(1), int8(1), int8(1), int8(1), int8(1)}}
count := 0
replacedVals := make([]int8, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachInt8(func(i int, val int8) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustInt8Slice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustInt8Slice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustInt8Slice()[2])
}
func TestWhereInt8(t *testing.T) {
m := objx.Map{"data": []int8{int8(1), int8(1), int8(1), int8(1), int8(1), int8(1)}}
selected := m.Get("data").WhereInt8(func(i int, val int8) bool {
return i%2 == 0
}).MustInt8Slice()
assert.Equal(t, 3, len(selected))
}
func TestGroupInt8(t *testing.T) {
m := objx.Map{"data": []int8{int8(1), int8(1), int8(1), int8(1), int8(1), int8(1)}}
grouped := m.Get("data").GroupInt8(func(i int, val int8) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]int8)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceInt8(t *testing.T) {
m := objx.Map{"data": []int8{int8(1), int8(1), int8(1), int8(1), int8(1), int8(1)}}
rawArr := m.Get("data").MustInt8Slice()
replaced := m.Get("data").ReplaceInt8(func(index int, val int8) int8 {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustInt8Slice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectInt8(t *testing.T) {
m := objx.Map{"data": []int8{int8(1), int8(1), int8(1), int8(1), int8(1), int8(1)}}
collected := m.Get("data").CollectInt8(func(index int, val int8) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Int16 (int16 and []int16)
*/
func TestInt16(t *testing.T) {
val := int16(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Int16())
assert.Equal(t, val, m.Get("value").MustInt16())
assert.Equal(t, int16(0), m.Get("nothing").Int16())
assert.Equal(t, val, m.Get("nothing").Int16(1))
assert.Panics(t, func() {
m.Get("age").MustInt16()
})
}
func TestInt16Slice(t *testing.T) {
val := int16(1)
m := objx.Map{"value": []int16{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").Int16Slice()[0])
assert.Equal(t, val, m.Get("value").MustInt16Slice()[0])
assert.Equal(t, []int16(nil), m.Get("nothing").Int16Slice())
assert.Equal(t, val, m.Get("nothing").Int16Slice([]int16{int16(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustInt16Slice()
})
}
func TestIsInt16(t *testing.T) {
m := objx.Map{"data": int16(1)}
assert.True(t, m.Get("data").IsInt16())
}
func TestIsInt16Slice(t *testing.T) {
m := objx.Map{"data": []int16{int16(1)}}
assert.True(t, m.Get("data").IsInt16Slice())
}
func TestEachInt16(t *testing.T) {
m := objx.Map{"data": []int16{int16(1), int16(1), int16(1), int16(1), int16(1)}}
count := 0
replacedVals := make([]int16, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachInt16(func(i int, val int16) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustInt16Slice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustInt16Slice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustInt16Slice()[2])
}
func TestWhereInt16(t *testing.T) {
m := objx.Map{"data": []int16{int16(1), int16(1), int16(1), int16(1), int16(1), int16(1)}}
selected := m.Get("data").WhereInt16(func(i int, val int16) bool {
return i%2 == 0
}).MustInt16Slice()
assert.Equal(t, 3, len(selected))
}
func TestGroupInt16(t *testing.T) {
m := objx.Map{"data": []int16{int16(1), int16(1), int16(1), int16(1), int16(1), int16(1)}}
grouped := m.Get("data").GroupInt16(func(i int, val int16) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]int16)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceInt16(t *testing.T) {
m := objx.Map{"data": []int16{int16(1), int16(1), int16(1), int16(1), int16(1), int16(1)}}
rawArr := m.Get("data").MustInt16Slice()
replaced := m.Get("data").ReplaceInt16(func(index int, val int16) int16 {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustInt16Slice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectInt16(t *testing.T) {
m := objx.Map{"data": []int16{int16(1), int16(1), int16(1), int16(1), int16(1), int16(1)}}
collected := m.Get("data").CollectInt16(func(index int, val int16) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Int32 (int32 and []int32)
*/
func TestInt32(t *testing.T) {
val := int32(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Int32())
assert.Equal(t, val, m.Get("value").MustInt32())
assert.Equal(t, int32(0), m.Get("nothing").Int32())
assert.Equal(t, val, m.Get("nothing").Int32(1))
assert.Panics(t, func() {
m.Get("age").MustInt32()
})
}
func TestInt32Slice(t *testing.T) {
val := int32(1)
m := objx.Map{"value": []int32{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").Int32Slice()[0])
assert.Equal(t, val, m.Get("value").MustInt32Slice()[0])
assert.Equal(t, []int32(nil), m.Get("nothing").Int32Slice())
assert.Equal(t, val, m.Get("nothing").Int32Slice([]int32{int32(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustInt32Slice()
})
}
func TestIsInt32(t *testing.T) {
m := objx.Map{"data": int32(1)}
assert.True(t, m.Get("data").IsInt32())
}
func TestIsInt32Slice(t *testing.T) {
m := objx.Map{"data": []int32{int32(1)}}
assert.True(t, m.Get("data").IsInt32Slice())
}
func TestEachInt32(t *testing.T) {
m := objx.Map{"data": []int32{int32(1), int32(1), int32(1), int32(1), int32(1)}}
count := 0
replacedVals := make([]int32, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachInt32(func(i int, val int32) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustInt32Slice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustInt32Slice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustInt32Slice()[2])
}
func TestWhereInt32(t *testing.T) {
m := objx.Map{"data": []int32{int32(1), int32(1), int32(1), int32(1), int32(1), int32(1)}}
selected := m.Get("data").WhereInt32(func(i int, val int32) bool {
return i%2 == 0
}).MustInt32Slice()
assert.Equal(t, 3, len(selected))
}
func TestGroupInt32(t *testing.T) {
m := objx.Map{"data": []int32{int32(1), int32(1), int32(1), int32(1), int32(1), int32(1)}}
grouped := m.Get("data").GroupInt32(func(i int, val int32) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]int32)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceInt32(t *testing.T) {
m := objx.Map{"data": []int32{int32(1), int32(1), int32(1), int32(1), int32(1), int32(1)}}
rawArr := m.Get("data").MustInt32Slice()
replaced := m.Get("data").ReplaceInt32(func(index int, val int32) int32 {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustInt32Slice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectInt32(t *testing.T) {
m := objx.Map{"data": []int32{int32(1), int32(1), int32(1), int32(1), int32(1), int32(1)}}
collected := m.Get("data").CollectInt32(func(index int, val int32) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Int64 (int64 and []int64)
*/
func TestInt64(t *testing.T) {
val := int64(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Int64())
assert.Equal(t, val, m.Get("value").MustInt64())
assert.Equal(t, int64(0), m.Get("nothing").Int64())
assert.Equal(t, val, m.Get("nothing").Int64(1))
assert.Panics(t, func() {
m.Get("age").MustInt64()
})
}
func TestInt64Slice(t *testing.T) {
val := int64(1)
m := objx.Map{"value": []int64{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").Int64Slice()[0])
assert.Equal(t, val, m.Get("value").MustInt64Slice()[0])
assert.Equal(t, []int64(nil), m.Get("nothing").Int64Slice())
assert.Equal(t, val, m.Get("nothing").Int64Slice([]int64{int64(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustInt64Slice()
})
}
func TestIsInt64(t *testing.T) {
m := objx.Map{"data": int64(1)}
assert.True(t, m.Get("data").IsInt64())
}
func TestIsInt64Slice(t *testing.T) {
m := objx.Map{"data": []int64{int64(1)}}
assert.True(t, m.Get("data").IsInt64Slice())
}
func TestEachInt64(t *testing.T) {
m := objx.Map{"data": []int64{int64(1), int64(1), int64(1), int64(1), int64(1)}}
count := 0
replacedVals := make([]int64, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachInt64(func(i int, val int64) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustInt64Slice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustInt64Slice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustInt64Slice()[2])
}
func TestWhereInt64(t *testing.T) {
m := objx.Map{"data": []int64{int64(1), int64(1), int64(1), int64(1), int64(1), int64(1)}}
selected := m.Get("data").WhereInt64(func(i int, val int64) bool {
return i%2 == 0
}).MustInt64Slice()
assert.Equal(t, 3, len(selected))
}
func TestGroupInt64(t *testing.T) {
m := objx.Map{"data": []int64{int64(1), int64(1), int64(1), int64(1), int64(1), int64(1)}}
grouped := m.Get("data").GroupInt64(func(i int, val int64) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]int64)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceInt64(t *testing.T) {
m := objx.Map{"data": []int64{int64(1), int64(1), int64(1), int64(1), int64(1), int64(1)}}
rawArr := m.Get("data").MustInt64Slice()
replaced := m.Get("data").ReplaceInt64(func(index int, val int64) int64 {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustInt64Slice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectInt64(t *testing.T) {
m := objx.Map{"data": []int64{int64(1), int64(1), int64(1), int64(1), int64(1), int64(1)}}
collected := m.Get("data").CollectInt64(func(index int, val int64) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Uint (uint and []uint)
*/
func TestUint(t *testing.T) {
val := uint(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Uint())
assert.Equal(t, val, m.Get("value").MustUint())
assert.Equal(t, uint(0), m.Get("nothing").Uint())
assert.Equal(t, val, m.Get("nothing").Uint(1))
assert.Panics(t, func() {
m.Get("age").MustUint()
})
}
func TestUintSlice(t *testing.T) {
val := uint(1)
m := objx.Map{"value": []uint{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").UintSlice()[0])
assert.Equal(t, val, m.Get("value").MustUintSlice()[0])
assert.Equal(t, []uint(nil), m.Get("nothing").UintSlice())
assert.Equal(t, val, m.Get("nothing").UintSlice([]uint{uint(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustUintSlice()
})
}
func TestIsUint(t *testing.T) {
m := objx.Map{"data": uint(1)}
assert.True(t, m.Get("data").IsUint())
}
func TestIsUintSlice(t *testing.T) {
m := objx.Map{"data": []uint{uint(1)}}
assert.True(t, m.Get("data").IsUintSlice())
}
func TestEachUint(t *testing.T) {
m := objx.Map{"data": []uint{uint(1), uint(1), uint(1), uint(1), uint(1)}}
count := 0
replacedVals := make([]uint, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachUint(func(i int, val uint) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustUintSlice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustUintSlice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustUintSlice()[2])
}
func TestWhereUint(t *testing.T) {
m := objx.Map{"data": []uint{uint(1), uint(1), uint(1), uint(1), uint(1), uint(1)}}
selected := m.Get("data").WhereUint(func(i int, val uint) bool {
return i%2 == 0
}).MustUintSlice()
assert.Equal(t, 3, len(selected))
}
func TestGroupUint(t *testing.T) {
m := objx.Map{"data": []uint{uint(1), uint(1), uint(1), uint(1), uint(1), uint(1)}}
grouped := m.Get("data").GroupUint(func(i int, val uint) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]uint)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceUint(t *testing.T) {
m := objx.Map{"data": []uint{uint(1), uint(1), uint(1), uint(1), uint(1), uint(1)}}
rawArr := m.Get("data").MustUintSlice()
replaced := m.Get("data").ReplaceUint(func(index int, val uint) uint {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustUintSlice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectUint(t *testing.T) {
m := objx.Map{"data": []uint{uint(1), uint(1), uint(1), uint(1), uint(1), uint(1)}}
collected := m.Get("data").CollectUint(func(index int, val uint) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Uint8 (uint8 and []uint8)
*/
func TestUint8(t *testing.T) {
val := uint8(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Uint8())
assert.Equal(t, val, m.Get("value").MustUint8())
assert.Equal(t, uint8(0), m.Get("nothing").Uint8())
assert.Equal(t, val, m.Get("nothing").Uint8(1))
assert.Panics(t, func() {
m.Get("age").MustUint8()
})
}
func TestUint8Slice(t *testing.T) {
val := uint8(1)
m := objx.Map{"value": []uint8{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").Uint8Slice()[0])
assert.Equal(t, val, m.Get("value").MustUint8Slice()[0])
assert.Equal(t, []uint8(nil), m.Get("nothing").Uint8Slice())
assert.Equal(t, val, m.Get("nothing").Uint8Slice([]uint8{uint8(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustUint8Slice()
})
}
func TestIsUint8(t *testing.T) {
m := objx.Map{"data": uint8(1)}
assert.True(t, m.Get("data").IsUint8())
}
func TestIsUint8Slice(t *testing.T) {
m := objx.Map{"data": []uint8{uint8(1)}}
assert.True(t, m.Get("data").IsUint8Slice())
}
func TestEachUint8(t *testing.T) {
m := objx.Map{"data": []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}}
count := 0
replacedVals := make([]uint8, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachUint8(func(i int, val uint8) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustUint8Slice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustUint8Slice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustUint8Slice()[2])
}
func TestWhereUint8(t *testing.T) {
m := objx.Map{"data": []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}}
selected := m.Get("data").WhereUint8(func(i int, val uint8) bool {
return i%2 == 0
}).MustUint8Slice()
assert.Equal(t, 3, len(selected))
}
func TestGroupUint8(t *testing.T) {
m := objx.Map{"data": []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}}
grouped := m.Get("data").GroupUint8(func(i int, val uint8) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]uint8)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceUint8(t *testing.T) {
m := objx.Map{"data": []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}}
rawArr := m.Get("data").MustUint8Slice()
replaced := m.Get("data").ReplaceUint8(func(index int, val uint8) uint8 {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustUint8Slice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectUint8(t *testing.T) {
m := objx.Map{"data": []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}}
collected := m.Get("data").CollectUint8(func(index int, val uint8) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Uint16 (uint16 and []uint16)
*/
func TestUint16(t *testing.T) {
val := uint16(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Uint16())
assert.Equal(t, val, m.Get("value").MustUint16())
assert.Equal(t, uint16(0), m.Get("nothing").Uint16())
assert.Equal(t, val, m.Get("nothing").Uint16(1))
assert.Panics(t, func() {
m.Get("age").MustUint16()
})
}
func TestUint16Slice(t *testing.T) {
val := uint16(1)
m := objx.Map{"value": []uint16{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").Uint16Slice()[0])
assert.Equal(t, val, m.Get("value").MustUint16Slice()[0])
assert.Equal(t, []uint16(nil), m.Get("nothing").Uint16Slice())
assert.Equal(t, val, m.Get("nothing").Uint16Slice([]uint16{uint16(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustUint16Slice()
})
}
func TestIsUint16(t *testing.T) {
m := objx.Map{"data": uint16(1)}
assert.True(t, m.Get("data").IsUint16())
}
func TestIsUint16Slice(t *testing.T) {
m := objx.Map{"data": []uint16{uint16(1)}}
assert.True(t, m.Get("data").IsUint16Slice())
}
func TestEachUint16(t *testing.T) {
m := objx.Map{"data": []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}}
count := 0
replacedVals := make([]uint16, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachUint16(func(i int, val uint16) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustUint16Slice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustUint16Slice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustUint16Slice()[2])
}
func TestWhereUint16(t *testing.T) {
m := objx.Map{"data": []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}}
selected := m.Get("data").WhereUint16(func(i int, val uint16) bool {
return i%2 == 0
}).MustUint16Slice()
assert.Equal(t, 3, len(selected))
}
func TestGroupUint16(t *testing.T) {
m := objx.Map{"data": []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}}
grouped := m.Get("data").GroupUint16(func(i int, val uint16) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]uint16)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceUint16(t *testing.T) {
m := objx.Map{"data": []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}}
rawArr := m.Get("data").MustUint16Slice()
replaced := m.Get("data").ReplaceUint16(func(index int, val uint16) uint16 {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustUint16Slice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectUint16(t *testing.T) {
m := objx.Map{"data": []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}}
collected := m.Get("data").CollectUint16(func(index int, val uint16) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Uint32 (uint32 and []uint32)
*/
func TestUint32(t *testing.T) {
val := uint32(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Uint32())
assert.Equal(t, val, m.Get("value").MustUint32())
assert.Equal(t, uint32(0), m.Get("nothing").Uint32())
assert.Equal(t, val, m.Get("nothing").Uint32(1))
assert.Panics(t, func() {
m.Get("age").MustUint32()
})
}
func TestUint32Slice(t *testing.T) {
val := uint32(1)
m := objx.Map{"value": []uint32{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").Uint32Slice()[0])
assert.Equal(t, val, m.Get("value").MustUint32Slice()[0])
assert.Equal(t, []uint32(nil), m.Get("nothing").Uint32Slice())
assert.Equal(t, val, m.Get("nothing").Uint32Slice([]uint32{uint32(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustUint32Slice()
})
}
func TestIsUint32(t *testing.T) {
m := objx.Map{"data": uint32(1)}
assert.True(t, m.Get("data").IsUint32())
}
func TestIsUint32Slice(t *testing.T) {
m := objx.Map{"data": []uint32{uint32(1)}}
assert.True(t, m.Get("data").IsUint32Slice())
}
func TestEachUint32(t *testing.T) {
m := objx.Map{"data": []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}}
count := 0
replacedVals := make([]uint32, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachUint32(func(i int, val uint32) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustUint32Slice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustUint32Slice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustUint32Slice()[2])
}
func TestWhereUint32(t *testing.T) {
m := objx.Map{"data": []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}}
selected := m.Get("data").WhereUint32(func(i int, val uint32) bool {
return i%2 == 0
}).MustUint32Slice()
assert.Equal(t, 3, len(selected))
}
func TestGroupUint32(t *testing.T) {
m := objx.Map{"data": []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}}
grouped := m.Get("data").GroupUint32(func(i int, val uint32) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]uint32)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceUint32(t *testing.T) {
m := objx.Map{"data": []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}}
rawArr := m.Get("data").MustUint32Slice()
replaced := m.Get("data").ReplaceUint32(func(index int, val uint32) uint32 {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustUint32Slice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectUint32(t *testing.T) {
m := objx.Map{"data": []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}}
collected := m.Get("data").CollectUint32(func(index int, val uint32) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Uint64 (uint64 and []uint64)
*/
func TestUint64(t *testing.T) {
val := uint64(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Uint64())
assert.Equal(t, val, m.Get("value").MustUint64())
assert.Equal(t, uint64(0), m.Get("nothing").Uint64())
assert.Equal(t, val, m.Get("nothing").Uint64(1))
assert.Panics(t, func() {
m.Get("age").MustUint64()
})
}
func TestUint64Slice(t *testing.T) {
val := uint64(1)
m := objx.Map{"value": []uint64{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").Uint64Slice()[0])
assert.Equal(t, val, m.Get("value").MustUint64Slice()[0])
assert.Equal(t, []uint64(nil), m.Get("nothing").Uint64Slice())
assert.Equal(t, val, m.Get("nothing").Uint64Slice([]uint64{uint64(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustUint64Slice()
})
}
func TestIsUint64(t *testing.T) {
m := objx.Map{"data": uint64(1)}
assert.True(t, m.Get("data").IsUint64())
}
func TestIsUint64Slice(t *testing.T) {
m := objx.Map{"data": []uint64{uint64(1)}}
assert.True(t, m.Get("data").IsUint64Slice())
}
func TestEachUint64(t *testing.T) {
m := objx.Map{"data": []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}}
count := 0
replacedVals := make([]uint64, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachUint64(func(i int, val uint64) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustUint64Slice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustUint64Slice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustUint64Slice()[2])
}
func TestWhereUint64(t *testing.T) {
m := objx.Map{"data": []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}}
selected := m.Get("data").WhereUint64(func(i int, val uint64) bool {
return i%2 == 0
}).MustUint64Slice()
assert.Equal(t, 3, len(selected))
}
func TestGroupUint64(t *testing.T) {
m := objx.Map{"data": []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}}
grouped := m.Get("data").GroupUint64(func(i int, val uint64) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]uint64)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceUint64(t *testing.T) {
m := objx.Map{"data": []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}}
rawArr := m.Get("data").MustUint64Slice()
replaced := m.Get("data").ReplaceUint64(func(index int, val uint64) uint64 {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustUint64Slice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectUint64(t *testing.T) {
m := objx.Map{"data": []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}}
collected := m.Get("data").CollectUint64(func(index int, val uint64) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Uintptr (uintptr and []uintptr)
*/
func TestUintptr(t *testing.T) {
val := uintptr(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Uintptr())
assert.Equal(t, val, m.Get("value").MustUintptr())
assert.Equal(t, uintptr(0), m.Get("nothing").Uintptr())
assert.Equal(t, val, m.Get("nothing").Uintptr(1))
assert.Panics(t, func() {
m.Get("age").MustUintptr()
})
}
func TestUintptrSlice(t *testing.T) {
val := uintptr(1)
m := objx.Map{"value": []uintptr{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").UintptrSlice()[0])
assert.Equal(t, val, m.Get("value").MustUintptrSlice()[0])
assert.Equal(t, []uintptr(nil), m.Get("nothing").UintptrSlice())
assert.Equal(t, val, m.Get("nothing").UintptrSlice([]uintptr{uintptr(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustUintptrSlice()
})
}
func TestIsUintptr(t *testing.T) {
m := objx.Map{"data": uintptr(1)}
assert.True(t, m.Get("data").IsUintptr())
}
func TestIsUintptrSlice(t *testing.T) {
m := objx.Map{"data": []uintptr{uintptr(1)}}
assert.True(t, m.Get("data").IsUintptrSlice())
}
func TestEachUintptr(t *testing.T) {
m := objx.Map{"data": []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}}
count := 0
replacedVals := make([]uintptr, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachUintptr(func(i int, val uintptr) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustUintptrSlice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustUintptrSlice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustUintptrSlice()[2])
}
func TestWhereUintptr(t *testing.T) {
m := objx.Map{"data": []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}}
selected := m.Get("data").WhereUintptr(func(i int, val uintptr) bool {
return i%2 == 0
}).MustUintptrSlice()
assert.Equal(t, 3, len(selected))
}
func TestGroupUintptr(t *testing.T) {
m := objx.Map{"data": []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}}
grouped := m.Get("data").GroupUintptr(func(i int, val uintptr) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]uintptr)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceUintptr(t *testing.T) {
m := objx.Map{"data": []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}}
rawArr := m.Get("data").MustUintptrSlice()
replaced := m.Get("data").ReplaceUintptr(func(index int, val uintptr) uintptr {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustUintptrSlice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectUintptr(t *testing.T) {
m := objx.Map{"data": []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}}
collected := m.Get("data").CollectUintptr(func(index int, val uintptr) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Float32 (float32 and []float32)
*/
func TestFloat32(t *testing.T) {
val := float32(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Float32())
assert.Equal(t, val, m.Get("value").MustFloat32())
assert.Equal(t, float32(0), m.Get("nothing").Float32())
assert.Equal(t, val, m.Get("nothing").Float32(1))
assert.Panics(t, func() {
m.Get("age").MustFloat32()
})
}
func TestFloat32Slice(t *testing.T) {
val := float32(1)
m := objx.Map{"value": []float32{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").Float32Slice()[0])
assert.Equal(t, val, m.Get("value").MustFloat32Slice()[0])
assert.Equal(t, []float32(nil), m.Get("nothing").Float32Slice())
assert.Equal(t, val, m.Get("nothing").Float32Slice([]float32{float32(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustFloat32Slice()
})
}
func TestIsFloat32(t *testing.T) {
m := objx.Map{"data": float32(1)}
assert.True(t, m.Get("data").IsFloat32())
}
func TestIsFloat32Slice(t *testing.T) {
m := objx.Map{"data": []float32{float32(1)}}
assert.True(t, m.Get("data").IsFloat32Slice())
}
func TestEachFloat32(t *testing.T) {
m := objx.Map{"data": []float32{float32(1), float32(1), float32(1), float32(1), float32(1)}}
count := 0
replacedVals := make([]float32, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachFloat32(func(i int, val float32) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustFloat32Slice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustFloat32Slice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustFloat32Slice()[2])
}
func TestWhereFloat32(t *testing.T) {
m := objx.Map{"data": []float32{float32(1), float32(1), float32(1), float32(1), float32(1), float32(1)}}
selected := m.Get("data").WhereFloat32(func(i int, val float32) bool {
return i%2 == 0
}).MustFloat32Slice()
assert.Equal(t, 3, len(selected))
}
func TestGroupFloat32(t *testing.T) {
m := objx.Map{"data": []float32{float32(1), float32(1), float32(1), float32(1), float32(1), float32(1)}}
grouped := m.Get("data").GroupFloat32(func(i int, val float32) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]float32)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceFloat32(t *testing.T) {
m := objx.Map{"data": []float32{float32(1), float32(1), float32(1), float32(1), float32(1), float32(1)}}
rawArr := m.Get("data").MustFloat32Slice()
replaced := m.Get("data").ReplaceFloat32(func(index int, val float32) float32 {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustFloat32Slice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectFloat32(t *testing.T) {
m := objx.Map{"data": []float32{float32(1), float32(1), float32(1), float32(1), float32(1), float32(1)}}
collected := m.Get("data").CollectFloat32(func(index int, val float32) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Float64 (float64 and []float64)
*/
func TestFloat64(t *testing.T) {
val := float64(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Float64())
assert.Equal(t, val, m.Get("value").MustFloat64())
assert.Equal(t, float64(0), m.Get("nothing").Float64())
assert.Equal(t, val, m.Get("nothing").Float64(1))
assert.Panics(t, func() {
m.Get("age").MustFloat64()
})
}
func TestFloat64Slice(t *testing.T) {
val := float64(1)
m := objx.Map{"value": []float64{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").Float64Slice()[0])
assert.Equal(t, val, m.Get("value").MustFloat64Slice()[0])
assert.Equal(t, []float64(nil), m.Get("nothing").Float64Slice())
assert.Equal(t, val, m.Get("nothing").Float64Slice([]float64{float64(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustFloat64Slice()
})
}
func TestIsFloat64(t *testing.T) {
m := objx.Map{"data": float64(1)}
assert.True(t, m.Get("data").IsFloat64())
}
func TestIsFloat64Slice(t *testing.T) {
m := objx.Map{"data": []float64{float64(1)}}
assert.True(t, m.Get("data").IsFloat64Slice())
}
func TestEachFloat64(t *testing.T) {
m := objx.Map{"data": []float64{float64(1), float64(1), float64(1), float64(1), float64(1)}}
count := 0
replacedVals := make([]float64, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachFloat64(func(i int, val float64) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustFloat64Slice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustFloat64Slice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustFloat64Slice()[2])
}
func TestWhereFloat64(t *testing.T) {
m := objx.Map{"data": []float64{float64(1), float64(1), float64(1), float64(1), float64(1), float64(1)}}
selected := m.Get("data").WhereFloat64(func(i int, val float64) bool {
return i%2 == 0
}).MustFloat64Slice()
assert.Equal(t, 3, len(selected))
}
func TestGroupFloat64(t *testing.T) {
m := objx.Map{"data": []float64{float64(1), float64(1), float64(1), float64(1), float64(1), float64(1)}}
grouped := m.Get("data").GroupFloat64(func(i int, val float64) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]float64)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceFloat64(t *testing.T) {
m := objx.Map{"data": []float64{float64(1), float64(1), float64(1), float64(1), float64(1), float64(1)}}
rawArr := m.Get("data").MustFloat64Slice()
replaced := m.Get("data").ReplaceFloat64(func(index int, val float64) float64 {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustFloat64Slice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectFloat64(t *testing.T) {
m := objx.Map{"data": []float64{float64(1), float64(1), float64(1), float64(1), float64(1), float64(1)}}
collected := m.Get("data").CollectFloat64(func(index int, val float64) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Complex64 (complex64 and []complex64)
*/
func TestComplex64(t *testing.T) {
val := complex64(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Complex64())
assert.Equal(t, val, m.Get("value").MustComplex64())
assert.Equal(t, complex64(0), m.Get("nothing").Complex64())
assert.Equal(t, val, m.Get("nothing").Complex64(1))
assert.Panics(t, func() {
m.Get("age").MustComplex64()
})
}
func TestComplex64Slice(t *testing.T) {
val := complex64(1)
m := objx.Map{"value": []complex64{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").Complex64Slice()[0])
assert.Equal(t, val, m.Get("value").MustComplex64Slice()[0])
assert.Equal(t, []complex64(nil), m.Get("nothing").Complex64Slice())
assert.Equal(t, val, m.Get("nothing").Complex64Slice([]complex64{complex64(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustComplex64Slice()
})
}
func TestIsComplex64(t *testing.T) {
m := objx.Map{"data": complex64(1)}
assert.True(t, m.Get("data").IsComplex64())
}
func TestIsComplex64Slice(t *testing.T) {
m := objx.Map{"data": []complex64{complex64(1)}}
assert.True(t, m.Get("data").IsComplex64Slice())
}
func TestEachComplex64(t *testing.T) {
m := objx.Map{"data": []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}}
count := 0
replacedVals := make([]complex64, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachComplex64(func(i int, val complex64) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustComplex64Slice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustComplex64Slice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustComplex64Slice()[2])
}
func TestWhereComplex64(t *testing.T) {
m := objx.Map{"data": []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}}
selected := m.Get("data").WhereComplex64(func(i int, val complex64) bool {
return i%2 == 0
}).MustComplex64Slice()
assert.Equal(t, 3, len(selected))
}
func TestGroupComplex64(t *testing.T) {
m := objx.Map{"data": []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}}
grouped := m.Get("data").GroupComplex64(func(i int, val complex64) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]complex64)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceComplex64(t *testing.T) {
m := objx.Map{"data": []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}}
rawArr := m.Get("data").MustComplex64Slice()
replaced := m.Get("data").ReplaceComplex64(func(index int, val complex64) complex64 {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustComplex64Slice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectComplex64(t *testing.T) {
m := objx.Map{"data": []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}}
collected := m.Get("data").CollectComplex64(func(index int, val complex64) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
/*
Tests for Complex128 (complex128 and []complex128)
*/
func TestComplex128(t *testing.T) {
val := complex128(1)
m := objx.Map{"value": val, "nothing": nil}
assert.Equal(t, val, m.Get("value").Complex128())
assert.Equal(t, val, m.Get("value").MustComplex128())
assert.Equal(t, complex128(0), m.Get("nothing").Complex128())
assert.Equal(t, val, m.Get("nothing").Complex128(1))
assert.Panics(t, func() {
m.Get("age").MustComplex128()
})
}
func TestComplex128Slice(t *testing.T) {
val := complex128(1)
m := objx.Map{"value": []complex128{val}, "nothing": nil}
assert.Equal(t, val, m.Get("value").Complex128Slice()[0])
assert.Equal(t, val, m.Get("value").MustComplex128Slice()[0])
assert.Equal(t, []complex128(nil), m.Get("nothing").Complex128Slice())
assert.Equal(t, val, m.Get("nothing").Complex128Slice([]complex128{complex128(1)})[0])
assert.Panics(t, func() {
m.Get("nothing").MustComplex128Slice()
})
}
func TestIsComplex128(t *testing.T) {
m := objx.Map{"data": complex128(1)}
assert.True(t, m.Get("data").IsComplex128())
}
func TestIsComplex128Slice(t *testing.T) {
m := objx.Map{"data": []complex128{complex128(1)}}
assert.True(t, m.Get("data").IsComplex128Slice())
}
func TestEachComplex128(t *testing.T) {
m := objx.Map{"data": []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}}
count := 0
replacedVals := make([]complex128, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachComplex128(func(i int, val complex128) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 3)
assert.Equal(t, replacedVals[0], m.Get("data").MustComplex128Slice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustComplex128Slice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustComplex128Slice()[2])
}
func TestWhereComplex128(t *testing.T) {
m := objx.Map{"data": []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}}
selected := m.Get("data").WhereComplex128(func(i int, val complex128) bool {
return i%2 == 0
}).MustComplex128Slice()
assert.Equal(t, 3, len(selected))
}
func TestGroupComplex128(t *testing.T) {
m := objx.Map{"data": []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}}
grouped := m.Get("data").GroupComplex128(func(i int, val complex128) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]complex128)
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestReplaceComplex128(t *testing.T) {
m := objx.Map{"data": []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}}
rawArr := m.Get("data").MustComplex128Slice()
replaced := m.Get("data").ReplaceComplex128(func(index int, val complex128) complex128 {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustComplex128Slice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestCollectComplex128(t *testing.T) {
m := objx.Map{"data": []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}}
collected := m.Get("data").CollectComplex128(func(index int, val complex128) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
objx-0.5.2/type_specific_test.go 0000664 0000000 0000000 00000047002 14570052437 0016706 0 ustar 00root root 0000000 0000000 package objx_test
import (
"fmt"
"testing"
"github.com/stretchr/objx"
"github.com/stretchr/testify/assert"
)
/*
Tests for MSI (map[string]interface{} and []map[string]interface{})
*/
func TestMSI(t *testing.T) {
val := map[string]interface{}(map[string]interface{}{"name": "Tyler"})
m := objx.Map{"value": val, "nothing": nil}
mVal := map[string]interface{}{"value": val, "nothing": nil}
assert.Equal(t, mVal, m.Value().MSI())
assert.Equal(t, val, m.Get("value").MSI())
assert.Equal(t, mVal, m.Value().MustMSI())
assert.Equal(t, val, m.Get("value").MustMSI())
assert.Equal(t, map[string]interface{}(nil), m.Get("nothing").MSI())
assert.Equal(t, val, m.Get("nothing").MSI(map[string]interface{}{"name": "Tyler"}))
assert.Panics(t, func() {
m.Get("age").MustMSI()
})
}
func TestMSISlice(t *testing.T) {
val := map[string]interface{}(map[string]interface{}{"name": "Tyler"})
m := objx.Map{
"value": []map[string]interface{}{val},
"value2": []objx.Map{val},
"value3": []interface{}{val},
"nothing": nil,
}
assert.Equal(t, val, m.Get("value").MSISlice()[0])
assert.Equal(t, val, m.Get("value2").MSISlice()[0])
assert.Equal(t, val, m.Get("value3").MSISlice()[0])
assert.Equal(t, val, m.Get("value").MustMSISlice()[0])
assert.Equal(t, val, m.Get("value2").MustMSISlice()[0])
assert.Equal(t, val, m.Get("value3").MustMSISlice()[0])
assert.Equal(t, []map[string]interface{}(nil), m.Get("nothing").MSISlice())
assert.Equal(t, val, m.Get("nothing").MSISlice([]map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"})})[0])
assert.Panics(t, func() {
m.Get("nothing").MustMSISlice()
})
o := objx.MustFromJSON(`{"d":[{"author":{"displayName":"DemoUser3","id":2},"classes":null,"id":9879,"v":{"code":"","created":"2013-09-19T09:38:50+02:00","published":"0001-01-01T00:00:00Z","updated":"2013-09-19T09:38:50+02:00"}}],"s":200}`)
assert.Equal(t, float64(9879), o.Get("d").MustMSISlice()[0]["id"])
assert.Equal(t, 1, len(o.Get("d").MSISlice()))
i := objx.MustFromJSON(`{"d":[{"author":"abc"},[1]]}`)
assert.Nil(t, i.Get("d").MSISlice())
}
func TestIsMSI(t *testing.T) {
m := objx.Map{"data": map[string]interface{}(map[string]interface{}{"name": "Tyler"})}
assert.True(t, m.Get("data").IsMSI())
assert.True(t, m.Value().IsMSI())
}
func TestIsMSISlice(t *testing.T) {
val := map[string]interface{}(map[string]interface{}{"name": "Tyler"})
m := objx.Map{"data": []map[string]interface{}{val}, "data2": []objx.Map{val}}
assert.True(t, m.Get("data").IsMSISlice())
assert.True(t, m.Get("data2").IsMSISlice())
o := objx.MustFromJSON(`{"d":[{"author":{"displayName":"DemoUser3","id":2},"classes":null,"id":9879,"v":{"code":"","created":"2013-09-19T09:38:50+02:00","published":"0001-01-01T00:00:00Z","updated":"2013-09-19T09:38:50+02:00"}}],"s":200}`)
assert.True(t, o.Has("d"))
assert.True(t, o.Get("d").IsMSISlice())
o = objx.MustFromJSON(`{"d":[{"author":"abc"},[1]]}`)
assert.True(t, o.Has("d"))
assert.False(t, o.Get("d").IsMSISlice())
}
func TestEachMSI(t *testing.T) {
m := objx.Map{"data": []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}}
count := 0
replacedVals := make([]map[string]interface{}, 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachMSI(func(i int, val map[string]interface{}) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
m2 := objx.Map{"data": []objx.Map{{"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}}}
assert.Equal(t, m2.Get("data"), m2.Get("data").EachMSI(func(i int, val map[string]interface{}) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 6)
assert.Equal(t, replacedVals[0], m.Get("data").MustMSISlice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustMSISlice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustMSISlice()[2])
assert.Equal(t, replacedVals[3], m2.Get("data").MustMSISlice()[0])
assert.Equal(t, replacedVals[4], m2.Get("data").MustMSISlice()[1])
assert.Equal(t, replacedVals[5], m2.Get("data").MustMSISlice()[2])
}
func TestWhereMSI(t *testing.T) {
m := objx.Map{"data": []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}}
selected := m.Get("data").WhereMSI(func(i int, val map[string]interface{}) bool {
return i%2 == 0
}).MustMSISlice()
assert.Equal(t, 3, len(selected))
}
func TestWhereMSI2(t *testing.T) {
m := objx.Map{"data": []objx.Map{{"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}}}
selected := m.Get("data").WhereMSI(func(i int, val map[string]interface{}) bool {
return i%2 == 0
}).MustMSISlice()
assert.Equal(t, 2, len(selected))
}
func TestGroupMSI(t *testing.T) {
m := objx.Map{"data": []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}}
grouped := m.Get("data").GroupMSI(func(i int, val map[string]interface{}) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]map[string]interface{})
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestGroupMSI2(t *testing.T) {
m := objx.Map{"data": []objx.Map{{"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}}}
grouped := m.Get("data").GroupMSI(func(i int, val map[string]interface{}) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][]map[string]interface{})
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 2, len(grouped["false"]))
}
func TestReplaceMSI(t *testing.T) {
m := objx.Map{"data": []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}}
rawArr := m.Get("data").MustMSISlice()
replaced := m.Get("data").ReplaceMSI(func(index int, val map[string]interface{}) map[string]interface{} {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustMSISlice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestReplaceMSI2(t *testing.T) {
m := objx.Map{"data": []objx.Map{{"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}}}
rawArr := m.Get("data").MustMSISlice()
replaced := m.Get("data").ReplaceMSI(func(index int, val map[string]interface{}) map[string]interface{} {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustMSISlice()
if assert.Equal(t, 5, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[0])
}
}
func TestCollectMSI(t *testing.T) {
m := objx.Map{"data": []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}}
collected := m.Get("data").CollectMSI(func(index int, val map[string]interface{}) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
func TestCollectMSI2(t *testing.T) {
m := objx.Map{"data": []objx.Map{{"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}, {"name": "Taylor"}}}
collected := m.Get("data").CollectMSI(func(index int, val map[string]interface{}) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 5, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
}
}
/*
Tests for ObjxMap ((objx.Map) and [](objx.Map))
*/
func TestObjxMap(t *testing.T) {
val := (objx.Map)(objx.New(1))
m := objx.Map{"value": val, "value2": map[string]interface{}{"name": "Taylor"}, "nothing": nil}
valMSI := objx.Map{"name": "Taylor"}
assert.Equal(t, val, m.Get("value").ObjxMap())
assert.Equal(t, valMSI, m.Get("value2").ObjxMap())
assert.Equal(t, val, m.Get("value").MustObjxMap())
assert.Equal(t, valMSI, m.Get("value2").MustObjxMap())
assert.Equal(t, (objx.Map)(objx.New(nil)), m.Get("nothing").ObjxMap())
assert.Equal(t, val, m.Get("nothing").ObjxMap(objx.New(1)))
assert.Panics(t, func() {
m.Get("age").MustObjxMap()
})
}
func TestObjxMapSlice(t *testing.T) {
val := (objx.Map)(objx.New(1))
m := objx.Map{
"value": [](objx.Map){val},
"value2": []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Taylor"})},
"value3": []interface{}{val},
"value4": []interface{}{map[string]interface{}(map[string]interface{}{"name": "Taylor"})},
"nothing": nil,
}
valMSI := objx.Map{"name": "Taylor"}
assert.Equal(t, val, m.Get("value").ObjxMapSlice()[0])
assert.Equal(t, valMSI, m.Get("value2").ObjxMapSlice()[0])
assert.Equal(t, val, m.Get("value3").ObjxMapSlice()[0])
assert.Equal(t, valMSI, m.Get("value4").ObjxMapSlice()[0])
assert.Equal(t, val, m.Get("value").MustObjxMapSlice()[0])
assert.Equal(t, valMSI, m.Get("value2").MustObjxMapSlice()[0])
assert.Equal(t, val, m.Get("value3").MustObjxMapSlice()[0])
assert.Equal(t, valMSI, m.Get("value4").MustObjxMapSlice()[0])
assert.Equal(t, [](objx.Map)(nil), m.Get("nothing").ObjxMapSlice())
assert.Equal(t, val, m.Get("nothing").ObjxMapSlice([](objx.Map){(objx.Map)(objx.New(1))})[0])
assert.Panics(t, func() {
m.Get("nothing").MustObjxMapSlice()
})
o := objx.MustFromJSON(`{"d":[{"author":{"displayName":"DemoUser3","id":2},"classes":null,"id":9879,"v":{"code":"","created":"2013-09-19T09:38:50+02:00","published":"0001-01-01T00:00:00Z","updated":"2013-09-19T09:38:50+02:00"}}],"s":200}`)
assert.Equal(t, 9879, o.Get("d").MustObjxMapSlice()[0].Get("id").Int())
assert.Equal(t, 1, len(o.Get("d").ObjxMapSlice()))
i := objx.MustFromJSON(`{"d":[{"author":"abc"},[1]]}`)
assert.Nil(t, i.Get("d").ObjxMapSlice())
}
func TestIsObjxMap(t *testing.T) {
m := objx.Map{"data": (objx.Map)(objx.New(1)), "data2": map[string]interface{}{"name": "Taylor"}}
assert.True(t, m.Get("data").IsObjxMap())
assert.True(t, m.Get("data2").IsObjxMap())
}
func TestIsObjxMapSlice(t *testing.T) {
m := objx.Map{"data": [](objx.Map){(objx.Map)(objx.New(1))}, "data2": []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Taylor"})}}
assert.True(t, m.Get("data").IsObjxMapSlice())
assert.True(t, m.Get("data2").IsObjxMapSlice())
o := objx.MustFromJSON(`{"d":[{"author":{"displayName":"DemoUser3","id":2},"classes":null,"id":9879,"v":{"code":"","created":"2013-09-19T09:38:50+02:00","published":"0001-01-01T00:00:00Z","updated":"2013-09-19T09:38:50+02:00"}}],"s":200}`)
assert.True(t, o.Has("d"))
assert.True(t, o.Get("d").IsObjxMapSlice())
// Valid json but not MSI slice
o = objx.MustFromJSON(`{"d":[{"author":"abc"},[1]]}`)
assert.True(t, o.Has("d"))
assert.False(t, o.Get("d").IsObjxMapSlice())
}
func TestEachObjxMap(t *testing.T) {
m := objx.Map{"data": [](objx.Map){(objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1))}}
count := 0
replacedVals := make([](objx.Map), 0)
assert.Equal(t, m.Get("data"), m.Get("data").EachObjxMap(func(i int, val objx.Map) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
m2 := objx.Map{"data": []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}}
assert.Equal(t, m2.Get("data"), m2.Get("data").EachObjxMap(func(i int, val objx.Map) bool {
count++
replacedVals = append(replacedVals, val)
// abort early
return i != 2
}))
assert.Equal(t, count, 6)
assert.Equal(t, replacedVals[0], m.Get("data").MustObjxMapSlice()[0])
assert.Equal(t, replacedVals[1], m.Get("data").MustObjxMapSlice()[1])
assert.Equal(t, replacedVals[2], m.Get("data").MustObjxMapSlice()[2])
assert.Equal(t, replacedVals[3], m2.Get("data").MustObjxMapSlice()[0])
assert.Equal(t, replacedVals[4], m2.Get("data").MustObjxMapSlice()[1])
assert.Equal(t, replacedVals[5], m2.Get("data").MustObjxMapSlice()[2])
}
func TestWhereObjxMap(t *testing.T) {
m := objx.Map{"data": [](objx.Map){(objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1))}}
selected := m.Get("data").WhereObjxMap(func(i int, val objx.Map) bool {
return i%2 == 0
}).MustObjxMapSlice()
assert.Equal(t, 3, len(selected))
}
func TestWhereObjxMap2(t *testing.T) {
m := objx.Map{"data": []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}}
selected := m.Get("data").WhereObjxMap(func(i int, val objx.Map) bool {
return i%2 == 0
}).MustObjxMapSlice()
assert.Equal(t, 2, len(selected))
}
func TestGroupObjxMap(t *testing.T) {
m := objx.Map{"data": [](objx.Map){(objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1))}}
grouped := m.Get("data").GroupObjxMap(func(i int, val objx.Map) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][](objx.Map))
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 3, len(grouped["false"]))
}
func TestGroupObjxMap2(t *testing.T) {
m := objx.Map{"data": []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}}
grouped := m.Get("data").GroupObjxMap(func(i int, val objx.Map) string {
return fmt.Sprintf("%v", i%2 == 0)
}).Data().(map[string][](objx.Map))
assert.Equal(t, 2, len(grouped))
assert.Equal(t, 3, len(grouped["true"]))
assert.Equal(t, 2, len(grouped["false"]))
}
func TestReplaceObjxMap(t *testing.T) {
m := objx.Map{"data": [](objx.Map){(objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1))}}
rawArr := m.Get("data").MustObjxMapSlice()
replaced := m.Get("data").ReplaceObjxMap(func(index int, val objx.Map) objx.Map {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustObjxMapSlice()
if assert.Equal(t, 6, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[5])
assert.Equal(t, replacedArr[5], rawArr[0])
}
}
func TestReplaceObjxMap2(t *testing.T) {
m := objx.Map{"data": []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}}
rawArr := m.Get("data").MustObjxMapSlice()
replaced := m.Get("data").ReplaceObjxMap(func(index int, val objx.Map) objx.Map {
if index < len(rawArr)-1 {
return rawArr[index+1]
}
return rawArr[0]
})
replacedArr := replaced.MustObjxMapSlice()
if assert.Equal(t, 5, len(replacedArr)) {
assert.Equal(t, replacedArr[0], rawArr[1])
assert.Equal(t, replacedArr[1], rawArr[2])
assert.Equal(t, replacedArr[2], rawArr[3])
assert.Equal(t, replacedArr[3], rawArr[4])
assert.Equal(t, replacedArr[4], rawArr[0])
}
}
func TestCollectObjxMap(t *testing.T) {
m := objx.Map{"data": [](objx.Map){(objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1)), (objx.Map)(objx.New(1))}}
collected := m.Get("data").CollectObjxMap(func(index int, val objx.Map) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 6, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
assert.Equal(t, collectedArr[5], 5)
}
}
func TestCollectObjxMap2(t *testing.T) {
m := objx.Map{"data": []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}}
collected := m.Get("data").CollectObjxMap(func(index int, val objx.Map) interface{} {
return index
})
collectedArr := collected.MustInterSlice()
if assert.Equal(t, 5, len(collectedArr)) {
assert.Equal(t, collectedArr[0], 0)
assert.Equal(t, collectedArr[1], 1)
assert.Equal(t, collectedArr[2], 2)
assert.Equal(t, collectedArr[3], 3)
assert.Equal(t, collectedArr[4], 4)
}
}
objx-0.5.2/value.go 0000664 0000000 0000000 00000007764 14570052437 0014150 0 ustar 00root root 0000000 0000000 package objx
import (
"fmt"
"strconv"
)
// Value provides methods for extracting interface{} data in various
// types.
type Value struct {
// data contains the raw data being managed by this Value
data interface{}
}
// Data returns the raw data contained by this Value
func (v *Value) Data() interface{} {
return v.data
}
// String returns the value always as a string
func (v *Value) String() string {
switch {
case v.IsNil():
return ""
case v.IsStr():
return v.Str()
case v.IsBool():
return strconv.FormatBool(v.Bool())
case v.IsFloat32():
return strconv.FormatFloat(float64(v.Float32()), 'f', -1, 32)
case v.IsFloat64():
return strconv.FormatFloat(v.Float64(), 'f', -1, 64)
case v.IsInt():
return strconv.FormatInt(int64(v.Int()), 10)
case v.IsInt8():
return strconv.FormatInt(int64(v.Int8()), 10)
case v.IsInt16():
return strconv.FormatInt(int64(v.Int16()), 10)
case v.IsInt32():
return strconv.FormatInt(int64(v.Int32()), 10)
case v.IsInt64():
return strconv.FormatInt(v.Int64(), 10)
case v.IsUint():
return strconv.FormatUint(uint64(v.Uint()), 10)
case v.IsUint8():
return strconv.FormatUint(uint64(v.Uint8()), 10)
case v.IsUint16():
return strconv.FormatUint(uint64(v.Uint16()), 10)
case v.IsUint32():
return strconv.FormatUint(uint64(v.Uint32()), 10)
case v.IsUint64():
return strconv.FormatUint(v.Uint64(), 10)
}
return fmt.Sprintf("%#v", v.Data())
}
// StringSlice returns the value always as a []string
func (v *Value) StringSlice(optionalDefault ...[]string) []string {
switch {
case v.IsStrSlice():
return v.MustStrSlice()
case v.IsBoolSlice():
slice := v.MustBoolSlice()
vals := make([]string, len(slice))
for i, iv := range slice {
vals[i] = strconv.FormatBool(iv)
}
return vals
case v.IsFloat32Slice():
slice := v.MustFloat32Slice()
vals := make([]string, len(slice))
for i, iv := range slice {
vals[i] = strconv.FormatFloat(float64(iv), 'f', -1, 32)
}
return vals
case v.IsFloat64Slice():
slice := v.MustFloat64Slice()
vals := make([]string, len(slice))
for i, iv := range slice {
vals[i] = strconv.FormatFloat(iv, 'f', -1, 64)
}
return vals
case v.IsIntSlice():
slice := v.MustIntSlice()
vals := make([]string, len(slice))
for i, iv := range slice {
vals[i] = strconv.FormatInt(int64(iv), 10)
}
return vals
case v.IsInt8Slice():
slice := v.MustInt8Slice()
vals := make([]string, len(slice))
for i, iv := range slice {
vals[i] = strconv.FormatInt(int64(iv), 10)
}
return vals
case v.IsInt16Slice():
slice := v.MustInt16Slice()
vals := make([]string, len(slice))
for i, iv := range slice {
vals[i] = strconv.FormatInt(int64(iv), 10)
}
return vals
case v.IsInt32Slice():
slice := v.MustInt32Slice()
vals := make([]string, len(slice))
for i, iv := range slice {
vals[i] = strconv.FormatInt(int64(iv), 10)
}
return vals
case v.IsInt64Slice():
slice := v.MustInt64Slice()
vals := make([]string, len(slice))
for i, iv := range slice {
vals[i] = strconv.FormatInt(iv, 10)
}
return vals
case v.IsUintSlice():
slice := v.MustUintSlice()
vals := make([]string, len(slice))
for i, iv := range slice {
vals[i] = strconv.FormatUint(uint64(iv), 10)
}
return vals
case v.IsUint8Slice():
slice := v.MustUint8Slice()
vals := make([]string, len(slice))
for i, iv := range slice {
vals[i] = strconv.FormatUint(uint64(iv), 10)
}
return vals
case v.IsUint16Slice():
slice := v.MustUint16Slice()
vals := make([]string, len(slice))
for i, iv := range slice {
vals[i] = strconv.FormatUint(uint64(iv), 10)
}
return vals
case v.IsUint32Slice():
slice := v.MustUint32Slice()
vals := make([]string, len(slice))
for i, iv := range slice {
vals[i] = strconv.FormatUint(uint64(iv), 10)
}
return vals
case v.IsUint64Slice():
slice := v.MustUint64Slice()
vals := make([]string, len(slice))
for i, iv := range slice {
vals[i] = strconv.FormatUint(iv, 10)
}
return vals
}
if len(optionalDefault) == 1 {
return optionalDefault[0]
}
return []string{}
}
objx-0.5.2/value_test.go 0000664 0000000 0000000 00000007052 14570052437 0015175 0 ustar 00root root 0000000 0000000 package objx_test
import (
"testing"
"github.com/stretchr/objx"
"github.com/stretchr/testify/assert"
)
func TestStringTypeString(t *testing.T) {
m := objx.Map{
"string": "foo",
}
assert.Equal(t, "foo", m.Get("string").String())
}
func TestStringTypeBool(t *testing.T) {
m := objx.Map{
"bool": true,
}
assert.Equal(t, "true", m.Get("bool").String())
}
func TestStringTypeInt(t *testing.T) {
m := objx.Map{
"int": int(1),
"int8": int8(8),
"int16": int16(16),
"int32": int32(32),
"int64": int64(64),
}
assert.Equal(t, "1", m.Get("int").String())
assert.Equal(t, "8", m.Get("int8").String())
assert.Equal(t, "16", m.Get("int16").String())
assert.Equal(t, "32", m.Get("int32").String())
assert.Equal(t, "64", m.Get("int64").String())
}
func TestStringTypeUint(t *testing.T) {
m := objx.Map{
"uint": uint(1),
"uint8": uint8(8),
"uint16": uint16(16),
"uint32": uint32(32),
"uint64": uint64(64),
}
assert.Equal(t, "1", m.Get("uint").String())
assert.Equal(t, "8", m.Get("uint8").String())
assert.Equal(t, "16", m.Get("uint16").String())
assert.Equal(t, "32", m.Get("uint32").String())
assert.Equal(t, "64", m.Get("uint64").String())
}
func TestStringTypeFloat(t *testing.T) {
m := objx.Map{
"float32": float32(32.32),
"float64": float64(64.64),
}
assert.Equal(t, "32.32", m.Get("float32").String())
assert.Equal(t, "64.64", m.Get("float64").String())
}
func TestStringTypeOther(t *testing.T) {
m := objx.Map{
"other": []string{"foo", "bar"},
"nilValue": nil,
}
assert.Equal(t, "[]string{\"foo\", \"bar\"}", m.Get("other").String())
assert.Equal(t, "", m.Get("nilValue").String())
}
func TestStringSliceTypeString(t *testing.T) {
m := objx.Map{
"string": []string{"foo", "bar"},
}
assert.Equal(t, []string{"foo", "bar"}, m.Get("string").StringSlice())
}
func TestStringSliceTypeBool(t *testing.T) {
m := objx.Map{
"bool": []bool{true, false},
}
assert.Equal(t, []string{"true", "false"}, m.Get("bool").StringSlice())
}
func TestStringSliceTypeInt(t *testing.T) {
m := objx.Map{
"int": []int{1, 2},
"int8": []int8{8, 9},
"int16": []int16{16, 17},
"int32": []int32{32, 33},
"int64": []int64{64, 65},
}
assert.Equal(t, []string{"1", "2"}, m.Get("int").StringSlice())
assert.Equal(t, []string{"8", "9"}, m.Get("int8").StringSlice())
assert.Equal(t, []string{"16", "17"}, m.Get("int16").StringSlice())
assert.Equal(t, []string{"32", "33"}, m.Get("int32").StringSlice())
assert.Equal(t, []string{"64", "65"}, m.Get("int64").StringSlice())
}
func TestStringSliceTypeUint(t *testing.T) {
m := objx.Map{
"uint": []uint{1, 2},
"uint8": []uint8{8, 9},
"uint16": []uint16{16, 17},
"uint32": []uint32{32, 33},
"uint64": []uint64{64, 65},
}
assert.Equal(t, []string{"1", "2"}, m.Get("uint").StringSlice())
assert.Equal(t, []string{"8", "9"}, m.Get("uint8").StringSlice())
assert.Equal(t, []string{"16", "17"}, m.Get("uint16").StringSlice())
assert.Equal(t, []string{"32", "33"}, m.Get("uint32").StringSlice())
assert.Equal(t, []string{"64", "65"}, m.Get("uint64").StringSlice())
}
func TestStringSliceTypeFloat(t *testing.T) {
m := objx.Map{
"float32": []float32{32.32, 33.33},
"float64": []float64{64.64, 65.65},
}
assert.Equal(t, []string{"32.32", "33.33"}, m.Get("float32").StringSlice())
assert.Equal(t, []string{"64.64", "65.65"}, m.Get("float64").StringSlice())
}
func TestStringSliceTypeOther(t *testing.T) {
m := objx.Map{
"other": "foo",
}
assert.Equal(t, []string{}, m.Get("other").StringSlice())
assert.Equal(t, []string{"bar"}, m.Get("other").StringSlice([]string{"bar"}))
}