Skip to content

Commit

Permalink
fix: add function
Browse files Browse the repository at this point in the history
  • Loading branch information
fupengl committed Jan 12, 2021
1 parent 5c19454 commit 2b063bd
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/function/get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { Dictionary, PropertyPath } from '../type';
import { isDef } from '../is';

function get<T>(
entity: Dictionary<T> | null | undefined,
...paths: PropertyPath[]
): T[keyof T] | undefined {
let current: any = entity;

for (let i = 0; i < paths.length; i += 1) {
if (isDef(current)) {
return undefined;
}

current = current[paths[i] as keyof T];
}

return current;
}

export default get;
2 changes: 2 additions & 0 deletions src/function/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { default as set } from './set';
export { default as get } from './get';
28 changes: 28 additions & 0 deletions src/function/set.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { PropertyPath } from '../type';

function set<Entity = any, Output = Entity, Value = any>(
entity: Entity,
paths: PropertyPath[],
value: Value,
): Output {
if (!paths.length) {
return (value as unknown) as Output;
}

const [path, ...restPath] = paths;

let clone: Output;
if (!entity && typeof path === 'number') {
clone = ([] as unknown) as Output;
} else if (Array.isArray(entity)) {
clone = ([...entity] as unknown) as Output;
} else {
clone = ({ ...entity } as unknown) as Output;
}

clone[path as string] = set(clone[path as string], restPath, value);

return clone;
}

export default set;
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export * from './dom';
export * from './bom';
export * from './date';
export * from './things';
export * from './function';
export * from './regex_constant';

export { default as noop } from './noop';
13 changes: 13 additions & 0 deletions src/type.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export type Many<T> = T | ReadonlyArray<T>;

export type PropertyName = string | number | symbol;

export type PropertyPath = Many<PropertyName>;

export interface Dictionary<T> {
[index: string]: T;
}

export interface NumericDictionary<T> {
[index: string]: T;
}

0 comments on commit 2b063bd

Please sign in to comment.