Strings
export const transform = (source: Record<string, any>): Record<string, any> => { return Object.fromEntries( Object.entries(source).map(([ key, value ]) => { const match = key.match(/^([^_]+)_(.+)$/); if (match) { return [ match[1], transform({ [match[2]]: value }) ]; } else { return [ key, value ]; } }), ); }
- export const transform = (source: Record<string, any>): Record<string, any> => {
const target = Object.create(null);// TODO: handle invalid propertyObject.entries(source).forEach(([key, value]) => {key.split("_").slice(0, -1).reduce((node: Record<string, any>, element: string) => {return node[element] ??= {};}, target)[key.slice(key.lastIndexOf("_") + 1)] = value;});return target;- return Object.fromEntries(
- Object.entries(source).map(([ key, value ]) => {
- const match = key.match(/^([^_]+)_(.+)$/);
- if (match) {
- return [ match[1], transform({ [match[2]]: value }) ];
- } else {
- return [ key, value ];
- }
- }),
- );
- }
// See https://www.chaijs.com for how to use Chai. import { assert } from "chai"; import { transform } from "./solution"; describe("object transformer function", () => { it("should handle single property", () => { const before = { a_b_c : 'value' } const after = { a : { b: { c: 'value' } } } assert.deepEqual(transform(before), after); }); it("should handle multiple property", () => { const before = { a_b_c : 'value', d:'value_d' } const after = { a : { b: { c: 'value' } }, d:'value_d' } assert.deepEqual(transform(before), after); }) it("should handle invalid property", () => { const before = { _: 'value' }; const after = { _:'value'}; assert.deepEqual(transform(before), after); }) it("should handle empty object", () => { const before = Object.create(null); const after = Object.create(null); assert.deepEqual(transform(before), after); }) });
- // See https://www.chaijs.com for how to use Chai.
- import { assert } from "chai";
- import { transform } from "./solution";
- describe("object transformer function", () => {
- it("should handle single property", () => {
- const before = { a_b_c : 'value' }
- const after = {
- a : {
- b: {
- c: 'value'
- }
- }
- }
- assert.deepEqual(transform(before), after);
- });
- it("should handle multiple property", () => {
- const before = { a_b_c : 'value', d:'value_d' }
- const after = {
- a : {
- b: {
- c: 'value'
- }
- },
- d:'value_d'
- }
- assert.deepEqual(transform(before), after);
- })
- it("should handle invalid property", () => {
- const before = { _: 'value' };
const after = { _:'value_d'};- const after = { _:'value'};
- assert.deepEqual(transform(before), after);
- })
- it("should handle empty object", () => {
- const before = Object.create(null);
- const after = Object.create(null);
- assert.deepEqual(transform(before), after);
- })
- });