ts-enum-util
ts-enum-util copied to clipboard
how to do asKeyOrDefault in case insensitive?
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')
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.
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.