Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(map): add GetOrSet for get value of exist key or set it #454

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

AuZhoomLee
Copy link

@AuZhoomLee AuZhoomLee commented May 18, 2024

GetOrSet is like setdefault(key, default=None) in Python for dict , and map.getOrDefault(Object key, V defaultValue) in Java for Map, returns the value of the given key or set the fallback value if not present.

@AuZhoomLee
Copy link
Author

AuZhoomLee commented May 18, 2024

Mostly, I used to collect value from another, but not sure has been set already, I will make sure first then to get it,

...
v, ok := kv[k]
if !ok {
    kv[k] = defaults.ConstantValue
}
...

In particular, I read config from environment variables or config file to get info, there will always be a default value to make sure essential value has been set for further using.

@lesichkovm
Copy link

Is this not the same as ValueOr ?

https://github.com/samber/lo?tab=readme-ov-file#valueor

@AuZhoomLee
Copy link
Author

Is this not the same as ValueOr ?

https://github.com/samber/lo?tab=readme-ov-file#valueor

@lesichkovm not same, ValueOr doesn't effect origin, this one can set default to origin

@lesichkovm
Copy link

lesichkovm commented Jul 6, 2024

@AuZhoomLee tahnk you for clarifying. Two points:

  1. I can see why this is useful. Its best to make it very clear we do modify the original map, as its kind of hidden. May be better name would help with this.

  2. Probably make the name similar to the current ValueOr so that they are alpahbetically ordered next to each other in the documentation, making it easier to be found by devs.

Possible options:

  • ValueOrSetDefault
  • ValueOrSetIfMissing
  • ValueOrSetMissing
  • ValueOrCreateMissing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants