Skip to content

Commit

Permalink
feat(core): adjust set() to have setMutate() and not return
Browse files Browse the repository at this point in the history
  • Loading branch information
nartc committed Jan 7, 2021
1 parent 7c4cf6f commit bdd6d17
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 5 deletions.
39 changes: 34 additions & 5 deletions packages/core/src/lib/utils/set.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,14 @@ export function set<T>(
path: string,
value: unknown
): (T & { [p: string]: unknown }) | T {
const decomposedPath = path.split('.');
const base = decomposedPath[0];
const { decomposedPath, base } = decomposePath(path);

if (base === undefined) {
return object;
}

// assign an empty object in order to spread object
if (!object.hasOwnProperty(base)) {
object[base] = {};
}
assignEmpty(object, base);

// Determine if there is still layers to traverse
value =
Expand All @@ -23,3 +20,35 @@ export function set<T>(

return Object.assign(object, { [base]: value });
}

export function setMutate<T>(object: T, path: string, value: unknown): void {
const { decomposedPath, base } = decomposePath(path);

if (base === undefined) {
return;
}

// assign an empty object in order to spread object
assignEmpty(object, base);

// Determine if there is still layers to traverse
if (decomposedPath.length <= 1) {
object[base] = value;
} else {
setMutate(object[base], decomposedPath.slice(1).join('.'), value);
}
}

function decomposePath(
path: string
): { decomposedPath: string[]; base: string } {
const decomposedPath = path.split('.');
const base = decomposedPath[0];
return { base, decomposedPath };
}

function assignEmpty<T>(obj: T, base: string) {
if (!obj.hasOwnProperty(base)) {
obj[base] = {};
}
}
26 changes: 26 additions & 0 deletions packages/core/src/lib/utils/specs/set.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,29 @@ describe('set', () => {
expect(result).toEqual({ foo: { bar: 'foo', baz: 'baz' } });
});
});

describe('setMutate', () => {
let obj: unknown;

beforeEach(() => {
obj = { foo: { bar: 'foo' } };
});

it('should set nested property', () => {
set(obj, 'foo.bar', 'baz');
expect(obj).toEqual({ foo: { bar: 'baz' } });
});

it('should set obj', () => {
set(obj, 'foo', { baz: 'foo' });
expect(obj).toEqual({ foo: { baz: 'foo' } });
});

it('should add property to obj at unknown path', () => {
set(obj, 'bar', 'foo');
expect(obj).toEqual({ foo: { bar: 'foo' }, bar: 'foo' });

set(obj, 'foo.baz', 'baz');
expect(obj).toEqual({ foo: { bar: 'foo', baz: 'baz' }, bar: 'foo' });
});
});

0 comments on commit bdd6d17

Please sign in to comment.