Skip to content

Commit

Permalink
fix: make enum lookup case insensitive (#3743)
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh Gummersall authored Jun 15, 2021
1 parent 87ecf38 commit eb2a383
Showing 1 changed file with 21 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,45 @@ type Input<T> = T | string | Expression;
* `string` to json [EnumExpression](xref:adaptive-expressions.EnumExpression) converter.
*/
export class EnumExpressionConverter<T> {
private _enumValue: unknown;
private readonly lowercaseIndex: Record<string, string>;

/**
* Initializes a new instance of the [EnumExpressionConverter](xref:adaptive-expressions.EnumExpressionConverter) class.
*
* @param enumValue The enum value of the `string` to convert.
*/
public constructor(enumValue: unknown) {
this._enumValue = enumValue;
constructor(private readonly enumValue: unknown) {
this.lowercaseIndex = Object.keys(enumValue || {}).reduce((acc, key) => {
acc[key.toLowerCase()] = key;

return acc;
}, {});
}

/**
* Converts a `string` into an [EnumExpression](xref:adaptive-expressions.EnumExpression).
*
* @param value `string` to convert.
* @returns The [EnumExpression](xref:adaptive-expressions.EnumExpression).
*/
public convert(value: Input<T> | EnumExpression<T>): EnumExpression<T> {
convert(value: Input<T> | EnumExpression<T>): EnumExpression<T> {
if (value instanceof EnumExpression) {
return value;
}
if (typeof value == 'string') {
if (Object.prototype.hasOwnProperty.call(this._enumValue, value)) {
return new EnumExpression<T>(this._enumValue[value as string]);

if (typeof value === 'string') {
let enumValue = this.enumValue[value];
if (enumValue === undefined) {
enumValue = this.enumValue[this.lowercaseIndex[value]];
}

if (enumValue !== undefined) {
return new EnumExpression<T>(enumValue as Input<T>);
}

return new EnumExpression<T>(`=${value}`);
}

return new EnumExpression<T>(value);
}
}

0 comments on commit eb2a383

Please sign in to comment.