Last active
September 9, 2022 23:37
-
-
Save jourdanrodrigues/6df1690dbe1c8234183cdeb4f4af6425 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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