Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to wirite lodash.merge by myself #318

Open
promotion-xu opened this issue Jun 17, 2021 · 0 comments
Open

How to wirite lodash.merge by myself #318

promotion-xu opened this issue Jun 17, 2021 · 0 comments
Labels

Comments

@promotion-xu
Copy link

promotion-xu commented Jun 17, 2021

export function merge<TTarget, TSource>(
  target: TTarget,
  source: TSource
): TTarget & TSource;
export function merge<ITarget, ISource1, ISource2>(
  target: ITarget,
  source1: ISource1,
  source2: ISource2
): ITarget & ISource1 & ISource2;
export function merge<ITarget, ISource extends { [key: string]: any }>(
  target: ITarget,
  ...args: ISource[]
): ITarget {
  return args.reduce((acc: ITarget, cur: ISource) => {
    return Object.keys(cur || {}).reduce((subAcc: any, key: string) => {
      const srcVal = cur[key];
      if (isObject(srcVal)) {
        subAcc[key] = merge(subAcc[key] ? subAcc[key] : {}, srcVal);
      } else if (Array.isArray(srcVal)) {
        // series: [],下层数组直接赋值
        subAcc[key] = srcVal.map((item, idx) => {
          if (isObject(item)) {
            const curAccVal = subAcc[key] ? subAcc[key] : [];
            return merge(curAccVal[idx] ? curAccVal[idx] : {}, item);
          } else {
            return item;
          }
        });
      } else {
        subAcc[key] = srcVal;
      }
      return subAcc;
    }, acc);
  }, target);
}

but I got an error,
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants