Skip to content

Commit

Permalink
feat(utilities): added to and from object utils
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewcourtice committed Aug 5, 2021
1 parent 8796aef commit 7989b82
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/utilities/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ export { default as Task } from './task/task';

export { default as clone } from './object/clone';
export { default as overwrite } from './object/overwrite';
export { default as fromPath } from './object/from-path';
export { default as toPath } from './object/to-path';

export { default as getType } from './type/get-type';
export { default as isArray } from './type/is-array';
Expand Down
6 changes: 6 additions & 0 deletions packages/utilities/src/object/from-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import isArray from '../type/is-array';

export default function fromPath<TValue extends object>(value: TValue, path: string | PropertyKey[]): object | undefined {
const nodes = isArray(path) ? path : path.split('/');
return nodes.reduce((branch, node) => (branch as any)?.[node], value);
}
11 changes: 11 additions & 0 deletions packages/utilities/src/object/to-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export default function toPath(nodes: PropertyKey[]): string {
return nodes.reduceRight((path, node) => {
const nodeStr = node.toString();

const segment = isNaN(parseInt(nodeStr, 10))
? `/${node.toString()}`
: `[${node.toString()}]`;

return segment + path.toString();
}, '').toString();
}

0 comments on commit 7989b82

Please sign in to comment.