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

how to do asKeyOrDefault in case insensitive? #26

Open
shtse8 opened this issue Jun 27, 2022 · 2 comments
Open

how to do asKeyOrDefault in case insensitive? #26

shtse8 opened this issue Jun 27, 2022 · 2 comments
Labels
question Further information is requested

Comments

@shtse8
Copy link

shtse8 commented Jun 27, 2022

I want to get the proper key (mixing upper and lower cases) from a string (lower case).
How can I do without looping through the whole array?

Here is my current implementation. Any better like using asKeyOrDefault ?

enum Languages {
  'unknown',
  'en',
  'zh-TW',
  'zh-CN',
  'ja',
}

const key = $enum(Languages).getKeys().find(x => x.toLowerCase() === 'zh-tw')
@UselessPickles UselessPickles added the question Further information is requested label Jun 27, 2022
@UselessPickles
Copy link
Owner

Everything in ts-enum-util related to key validation/comparison is case sensitive, so there's no direct support for what you want to do.

Your solution seems reasonable, unless you test and identify it to be a source of a performance issue. If you need to optimize it, then I would suggest building a lookup object whose keys are the lowercased keys of your enum, and the values are the original keys of the enum (build it once and store it for reuse). Then when you need to perform a case-insensitive conversion from a string to a valid key, you can lowercase the string and do a simple lookup into the object.

@shtse8
Copy link
Author

shtse8 commented Jun 30, 2022

will there be possible to support this in the future? adding an option to matching in case-insensitive mode.
I might help if it is the direction.

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

No branches or pull requests

2 participants