ts-enum-util icon indicating copy to clipboard operation
ts-enum-util copied to clipboard

how to do asKeyOrDefault in case insensitive?

Open shtse8 opened this issue 2 years ago • 2 comments

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')

shtse8 avatar Jun 27 '22 08:06 shtse8

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.

UselessPickles avatar Jun 27 '22 16:06 UselessPickles

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.

shtse8 avatar Jun 30 '22 11:06 shtse8