Skip to content

Instantly share code, notes, and snippets.

@jourdanrodrigues
Last active September 9, 2022 23:37
Show Gist options
  • Save jourdanrodrigues/6df1690dbe1c8234183cdeb4f4af6425 to your computer and use it in GitHub Desktop.
Save jourdanrodrigues/6df1690dbe1c8234183cdeb4f4af6425 to your computer and use it in GitHub Desktop.
import { defaultObject } from './defaultObject';
describe('defaultObject', () => {
it('should assign default values based on the provided factory', () => {
const output = defaultObject(() => [] as string[]);
output.id.push('3');
expect(cleanupProxy(output)).toEqual({ id: ['3'] });
});
it('should handle nested calls "defaultObject"', () => {
const output = defaultObject(() => defaultObject(() => 4));
output.layer1.layer2 += 3;
expect(cleanupProxy(output)).toEqual({ layer1: { layer2: 7 } });
});
});
export function cleanupProxy<T extends Object>(object: T): T {
return Object.entries({ ...object }).reduce((output, [key, value]) => {
const shouldClean = typeof value === 'object' && !Array.isArray(value);
return { ...output, [key]: shouldClean ? cleanupProxy(value) : value };
}, {} as T);
}
export function defaultObject<T extends any>(
factory: () => T
): { [key: string]: T } {
return new Proxy(
{},
{
get(target: { [key: string]: T }, key: string) {
if (!(key in target)) {
target[key] = factory();
}
return target[key];
},
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment