2019-10-30 23:26:57 +08:00
|
|
|
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
|
|
|
|
|
|
|
package gutil
|
|
|
|
|
2019-11-07 11:32:25 +08:00
|
|
|
import (
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
// replaceCharReg is the regular expression object for replacing chars in map keys.
|
|
|
|
replaceCharReg, _ = regexp.Compile(`[\-\.\_\s]+`)
|
|
|
|
)
|
|
|
|
|
2020-03-28 00:37:23 +08:00
|
|
|
// CopyMap does a shallow copy from map <data> to <copy> for most commonly used map type
|
|
|
|
// map[string]interface{}.
|
|
|
|
func CopyMap(data map[string]interface{}) (copy map[string]interface{}) {
|
2019-10-30 23:26:57 +08:00
|
|
|
copy = make(map[string]interface{}, len(data))
|
|
|
|
for k, v := range data {
|
|
|
|
copy[k] = v
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2019-11-07 11:32:25 +08:00
|
|
|
|
2019-12-04 16:04:52 +08:00
|
|
|
// MapPossibleItemByKey tries to find the possible key-value pair for given key with or without
|
2019-11-07 11:32:25 +08:00
|
|
|
// cases or chars '-'/'_'/'.'/' '.
|
|
|
|
//
|
|
|
|
// Note that this function might be of low performance.
|
2019-12-04 16:04:52 +08:00
|
|
|
func MapPossibleItemByKey(data map[string]interface{}, key string) (string, interface{}) {
|
2019-11-07 11:32:25 +08:00
|
|
|
if v, ok := data[key]; ok {
|
2019-12-04 16:04:52 +08:00
|
|
|
return key, v
|
2019-11-07 11:32:25 +08:00
|
|
|
}
|
|
|
|
replacedKey := replaceCharReg.ReplaceAllString(key, "")
|
|
|
|
if v, ok := data[replacedKey]; ok {
|
2019-12-04 16:04:52 +08:00
|
|
|
return replacedKey, v
|
2019-11-07 11:32:25 +08:00
|
|
|
}
|
|
|
|
// Loop for check.
|
|
|
|
for k, v := range data {
|
2020-03-28 21:32:29 +08:00
|
|
|
// Remove all special chars and compare with case insensitive.
|
2019-11-07 11:32:25 +08:00
|
|
|
if strings.EqualFold(replaceCharReg.ReplaceAllString(k, ""), replacedKey) {
|
2019-12-04 16:04:52 +08:00
|
|
|
return k, v
|
2019-11-07 11:32:25 +08:00
|
|
|
}
|
|
|
|
}
|
2019-12-04 16:04:52 +08:00
|
|
|
return "", nil
|
2019-11-07 11:32:25 +08:00
|
|
|
}
|