Skip to content

Instantly share code, notes, and snippets.

@dartess
Created April 29, 2022 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dartess/a5dbe0f00bd1a8dfdca7ec67eef820a7 to your computer and use it in GitHub Desktop.
Save dartess/a5dbe0f00bd1a8dfdca7ec67eef820a7 to your computer and use it in GitHub Desktop.
caseInsensitiveProxy
import { caseInsensitiveProxy } from '../caseInsensitiveProxy';
describe('caseInsensitiveProxy', () => {
it('set and get', () => {
const proxy = caseInsensitiveProxy<Record<string, unknown>>();
proxy.someValue = 1;
expect(proxy.someValue).toBe(1);
expect(proxy.SomeValUE).toBe(1);
expect(proxy.somevalue).toBe(1);
expect(proxy.ahother).toBe(undefined);
proxy.foO = 2;
expect(proxy.foo).toBe(2);
expect(proxy.foO).toBe(2);
expect(proxy.FOO).toBe(2);
});
it('with exist object', () => {
const proxy = caseInsensitiveProxy<Record<string, unknown>>({ someValue: 1 });
expect(proxy.someValue).toBe(1);
expect(proxy.SomeValUE).toBe(1);
expect(proxy.somevalue).toBe(1);
expect(proxy.ahother).toBe(undefined);
proxy.foO = 2;
expect(proxy.foo).toBe(2);
expect(proxy.foO).toBe(2);
expect(proxy.FOO).toBe(2);
});
it('in operator', () => {
const proxy = caseInsensitiveProxy<Record<string, unknown>>({ someValue: 1 });
expect('someValue' in proxy).toBe(true);
expect('SomeValUE' in proxy).toBe(true);
expect('somevalue' in proxy).toBe(true);
expect('ahother' in proxy).toBe(false);
});
it('delete operator', () => {
const proxy = caseInsensitiveProxy<Record<string, unknown>>({ someValue: 1 });
expect('someValue' in proxy).toBe(true);
delete proxy.someValue;
expect('someValue' in proxy).toBe(false);
});
});
export function caseInsensitiveProxy<T extends object>(source?: T): T {
const proxyTarget = {} as T;
if (source) {
Object.entries(source).forEach(([key, value]) => {
proxyTarget[key.toUpperCase() as keyof T] = value;
});
}
const tryCapitalize = (prop: string | symbol): string | symbol => {
return typeof prop === 'string' ? prop.toUpperCase() : prop;
};
return new Proxy(proxyTarget, {
get(target, prop, receiver) {
return Reflect.get(target, tryCapitalize(prop), receiver);
},
set(target, prop, value) {
return Reflect.set(target, tryCapitalize(prop), value);
},
defineProperty(target, prop, descriptor) {
return Reflect.defineProperty(target, tryCapitalize(prop), descriptor);
},
deleteProperty(target, prop) {
return Reflect.deleteProperty(target, tryCapitalize(prop));
},
getOwnPropertyDescriptor(target, prop) {
return Reflect.getOwnPropertyDescriptor(target, tryCapitalize(prop));
},
has(target, prop) {
return Reflect.has(target, tryCapitalize(prop));
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment