lodash#cloneDeep TypeScript Examples

The following examples show how to use lodash#cloneDeep. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: snapshots-utils.ts    From ui5-language-assistant with Apache License 2.0 7 votes vote down vote up
function cleanupLSPResponseForAssertions(
  diagnostics: Diagnostic[]
): Diagnostic[] {
  // side effect free
  const clonedDiagnostics = cloneDeep(diagnostics);
  forEach(clonedDiagnostics, (_) => {
    // Platform / Machine indepednet "formatting" for the related information uri.
    // e.g: avoid `/` vs `\` or absolute paths of specific users file system structure.
    forEach(_.relatedInformation, (info) => {
      const uriSuffixMatch = /.+(snapshots.*)/.exec(info.location.uri);
      if (uriSuffixMatch === null) {
        throw Error(
          "Failure computing a relatedInformation URI for snapshots!"
        );
      }
      const uriSuffixWithForwardSlash = uriSuffixMatch[1].replace(/\\/g, "/");
      info.location.uri = uriSuffixWithForwardSlash;
    });
    return _;
  });

  return clonedDiagnostics;
}
Example #2
Source File: utility.service.ts    From fyle-mobile-app with MIT License 7 votes vote down vote up
sortAllAdvances(sortDir: SortingDirection, sortParam: SortingParam, advancesArray: any[]) {
    //used for sorting an array that has both advances and advance requests mixed together
    const sortedAdvancesArray = cloneDeep(advancesArray);

    return sortedAdvancesArray.sort((advance1, advance2) => {
      const sortingValue1 = this.getSortingValue(advance1, sortParam);
      const sortingValue2 = this.getSortingValue(advance2, sortParam);
      return this.compareSortingValues(sortingValue1, sortingValue2, sortDir, sortParam);
    });
  }
Example #3
Source File: utils.ts    From gant-design with MIT License 7 votes vote down vote up
export function getRowsToUpdate(nodes, parentPath, createConfig, agGridConfig) {
  let res = [];
  let oldRowData = [];
  const { path, toPath, id } = createConfig;
  nodes.map(node => {
    let itemData = cloneDeep(node.data);
    let newPath = [];
    if (node.data) {
      itemData[path] = toPath(parentPath, itemData);
      newPath = agGridConfig.getDataPath(itemData);
      const { _rowCut, ...data } = itemData;
      res = res.concat([data]);
      oldRowData = oldRowData.concat([node.data]);
    }
    if (node.childrenAfterGroup) {
      let { newRowData: childrenNewRowData, oldRowData: childrenOldRowData } = getRowsToUpdate(
        node.childrenAfterGroup,
        newPath,
        createConfig,
        agGridConfig,
      );
      res = res.concat(childrenNewRowData);
      oldRowData = oldRowData.concat(childrenOldRowData);
    }
  });
  return { newRowData: res, oldRowData };
}
Example #4
Source File: search-map-getter.ts    From one-platform with MIT License 6 votes vote down vote up
/**
 * Get a nested value from an object/array using a string selector
 * @param data the input data object
 * @param prop the property selector
 * @param options additional options for response
 * @returns the object matching the selector, or null if nothing found
 */
export default function getValueBySelector(data: any, prop: string, opts: IOptions = { stringify: false }): any | null {
  const { stringify, fallback } = opts;
  const propsArray = prop
    .replace(/\[(\w+)\]/g, '.$1')
    .replace(/^\./, '')
    .split('.');

  let cursor = cloneDeep(data);
  try {
    const res = propsArray.reduce((value, propName) => {
      if (propName in cursor) {
        cursor = cursor[propName];
        return cursor;
      }
      logger.info('throwing...');
      throw new Error(`${propName} is not a property of ${typeof cursor}`);
    }, null);

    if (!isEmpty(res) && !isString(res) && stringify) {
      return JSON.stringify(res);
    }
    return res;
  } catch (err) {
    logger.debug(err);
    if (fallback) {
      return fallback;
    }
    throw err;
  }
}
Example #5
Source File: optimize.ts    From sc2-planner with MIT License 6 votes vote down vote up
/**
     * Adds supply to a bo wherever it's needed
     * gamelogic is assumed to have been run until the end
     */
    addSupply(gamelogic: GameLogic): [GameLogic, number] {
        const supplyItem = supplyUnitNameByRace[this.race]
        let addedSupply = 0
        let validatesConstraints = true
        while (
            addedSupply < 15 &&
            validatesConstraints &&
            gamelogic.errorMessage &&
            isEqual(gamelogic.requirements, [supplyItem])
        ) {
            // Start getting additional supply 1 bo item before the one needing it
            const bo = cloneDeep(gamelogic.bo)
            bo.splice(gamelogic.boIndex - 1, 0, <IBuildOrderElement>cloneDeep(supplyItem)) //TODO2 minus [0, 1, 2, 3] should be tested here for perfect results, not just minus [1]
            addedSupply += 1
            gamelogic = this.simulateBo(bo)
            validatesConstraints = this.validatedConstraints(gamelogic)
        }
        return [gamelogic, addedSupply]
    }
Example #6
Source File: BaseChart.ts    From anichart.js with MIT License 6 votes vote down vote up
setMeta() {
    if (recourse.data.get(this.metaName)) {
      this.meta = rollup(
        cloneDeep(recourse.data.get(this.metaName)),
        (v) => v[0],
        (d) => (d as any)[this.idField]
      );
    }
  }
Example #7
Source File: main.ts    From SpaceEye with MIT License 6 votes vote down vote up
// Send HEAD requests to each DNS IP, using the IP first to respond
Axios.interceptors.request.use(async config => {
    const newConfig = cloneDeep(config)
    const requestUrl = new url.URL(config.url!)
    if (net.isIP(requestUrl.hostname)) {
        return config
    }
    const ip = await resolveDns(requestUrl, config.cancelToken)
    newConfig.headers = config.headers ?? {}
    newConfig.headers.Host = requestUrl.hostname
    requestUrl.hostname = ip
    newConfig.url = requestUrl.toString()
    return newConfig
})
Example #8
Source File: util.ts    From redux-with-domain with MIT License 6 votes vote down vote up
export function initInitialState(module, pkg) {
  const { initialState = {} } = pkg
  module._initialState = cloneDeep(initialState)
  module._initialState['@@loading'] = {}
}
Example #9
Source File: xml-view-diagnostics.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
export function getXMLViewDiagnostics(opts: {
  document: TextDocument;
  ui5Model: UI5SemanticModel;
  flexEnabled?: boolean;
}): Diagnostic[] {
  const documentText = opts.document.getText();
  const { cst, tokenVector } = parse(documentText);
  const xmlDocAst = buildAst(cst as DocumentCstNode, tokenVector);
  const actualValidators = cloneDeep(defaultValidators);
  if (opts.flexEnabled) {
    actualValidators.element.push(validators.validateNonStableId);
  }
  const issues = validateXMLView({
    validators: actualValidators,
    xmlView: xmlDocAst,
    model: opts.ui5Model,
  });
  const diagnostics = validationIssuesToLspDiagnostics(issues, opts.document);
  return diagnostics;
}
Example #10
Source File: team.ts    From fishbowl with MIT License 6 votes vote down vote up
export function teamsWithSequence(players: Players) {
  const shuffledPlayers = shuffle(players)
  const halfLength = Math.ceil(shuffledPlayers.length / 2)
  const redTeam = addTeamAndSequence(
    cloneDeep(shuffledPlayers).splice(0, halfLength),
    Team.Red
  )
  const blueTeam = addTeamAndSequence(
    cloneDeep(shuffledPlayers).splice(halfLength, shuffledPlayers.length),
    Team.Blue
  )
  return redTeam.concat(blueTeam)
}
Example #11
Source File: ExampleList.tsx    From plugin-vscode with Apache License 2.0 6 votes vote down vote up
constructor(props: SamplesListProps, context: SamplesListState) {
        super(props, context);
        this.onSearchQueryEdit = debounce(() => {
            const { searchQuery } = this.state;
            if (searchQuery !== undefined && this.availableSamples) {
                let samples = cloneDeep(this.availableSamples);
                samples = samples.filter((sampleCategory) => {
                    if (!sampleCategory.title.toLowerCase().includes(searchQuery)) {
                        sampleCategory.samples = sampleCategory
                            .samples.filter((sample) => sample.name.toLowerCase().includes(searchQuery));
                    }
                    return sampleCategory.samples.length !== 0;
                });
                if (samples.length === 0) {
                    samples = cloneDeep(this.availableSamples);
                    this.setState({
                        noSearchReults: true
                    });
                } else {
                    this.setState({
                        noSearchReults: false
                    });
                }
                this.setState({
                    samples,
                });
            }
        }, 500).bind(this);
    }
Example #12
Source File: worker.ts    From omegga with ISC License 6 votes vote down vote up
// add plugin fetcher
omegga.getPlugin = async name => {
  let plugin = (await emit('getPlugin', name)) as PluginInterop & {
    emitPlugin(event: string, ...args: any[]): Promise<any>;
  };
  if (plugin) {
    plugin.emitPlugin = async (ev: string, ...args: any[]) => {
      return await emit('emitPlugin', name, ev, cloneDeep(args));
    };
    return plugin;
  } else {
    return null;
  }
};
Example #13
Source File: BoardUtils.ts    From Twenty48 with GNU General Public License v3.0 6 votes vote down vote up
transposeGrid = (grid: tBoard): tBoard => {
  // prefers const error
  // eslint-disable-next-line
  let newGrid = cloneDeep(DEFAULT_GAMEBOARD);
  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < 4; j++) {
      newGrid[i][j] = grid[j][i]
    }
  }
  return newGrid
}
Example #14
Source File: processor.ts    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
categoryMenuV2 = (
  categoryGroups: CategoryGroup[]
): Promise<SidebarMenu> => {
  const groups = cloneDeep(categoryGroups);
  const menuItems: SidebarMenuItem[] = [
    {
      text: i18next.t(`${NS_DEVELOPERS}:${K.ALL}`),
      to: "/developers/brick-book?category=",
      exact: true,
      activeMatchSearch: true,
    },
  ];
  let i = 1;
  groups.forEach((menu) => {
    menuItems.push({
      title: i18nText(menu.title),
      type: "group",
      items: [],
    });

    menu.items.forEach((book: Chapter) => {
      (menuItems[i] as SidebarMenuGroup).items.push({
        text: i18nText(book.title),
        to: `/developers/brick-book?category=${book.category}`,
        exact: true,
        activeMatchSearch: true,
      });
    });
    i += 1;
  });

  return Promise.resolve({
    title: "",
    menuItems: menuItems,
  });
}
Example #15
Source File: Kernel.ts    From next-core with GNU General Public License v3.0 6 votes vote down vote up
getStandaloneMenus(menuId: string): MenuRawData[] {
    const currentAppId = this.currentApp.id;
    const currentStoryboard = this.bootstrapData.storyboards.find(
      (storyboard) => storyboard.app.id === currentAppId
    );
    return (cloneDeep(currentStoryboard.meta?.menus) ?? [])
      .filter((menu) => menu.menuId === menuId)
      .map((menu) => ({
        ...menu,
        app: [{ appId: currentAppId }],
      }));
  }
Example #16
Source File: produce.ts    From yugong with MIT License 6 votes vote down vote up
export function saveRecord(name: string) {
  if (recordTimer) window.clearTimeout(recordTimer);
  if (!store.getState().record.isRecordReady) return;
  recordTimer = window.setTimeout(() => {
    const { runningTimes, appData, pageData } = store.getState();
    store.dispatch.record.setRecord({
      desc: name,
      runningTimes: cloneDeep(runningTimes),
      appData: cloneDeep(appData),
      pageData: cloneDeep(pageData),
    })
  }, 3000);
}
Example #17
Source File: create-add-on.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
private triggerGroupTab = (name: string) => {
    const { packUpTabs } = this.state;

    if (packUpTabs.has(name)) {
      packUpTabs.delete(name);
    } else {
      packUpTabs.add(name);
    }

    this.setState({
      packUpTabs: cloneDeep(packUpTabs),
    });
  };
Example #18
Source File: eip1.ts    From EIP-Bot with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
EIP1Purifier = (testResults: TestResults) => {
  const { errors } = cloneDeep(testResults);
  const eipNum = testResults.fileDiff.base.eipNum;

  if (eipNum === 1) {
    // authors not required for EIP1
    errors.approvalErrors.isAuthorApprovedError = undefined;
    // eip-1 doesn't have authors that are discernible so it can be ignored
    errors.authorErrors.hasAuthorsError = undefined;
    // this is a repeat of hasEnoughEditorApprovals
    errors.approvalErrors.isEditorApprovedError = undefined;
    // eip-1 must be reviewed by multiple editors, so we can allowed it to be
    // any status without saying so
    errors.headerErrors.validStatusError = undefined;
  } else {
    errors.approvalErrors.enoughEditorApprovalsForEIP1Error = undefined;
  }

  // clear error in all other cases
  return { ...testResults, errors };
}
Example #19
Source File: duplicate-detection.service.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
getPossibleDuplicates(transaction) {
    return this.orgUserSettingsService.get().pipe(
      switchMap((orgUserSettings) => {
        const localeOffset = orgUserSettings.locale.offset;

        const transactionCopy = cloneDeep(transaction);

        if (transactionCopy.tax) {
          delete transactionCopy.tax;
        }

        transactionCopy.txn_dt.setHours(12);
        transactionCopy.txn_dt.setMinutes(0);
        transactionCopy.txn_dt.setSeconds(0);
        transactionCopy.txn_dt.setMilliseconds(0);
        transactionCopy.txn_dt = this.timezoneService.convertToUtc(transactionCopy.txn_dt, localeOffset);
        if (transactionCopy.to_dt) {
          transactionCopy.to_dt.setHours(12);
          transactionCopy.to_dt.setMinutes(0);
          transactionCopy.to_dt.setSeconds(0);
          transactionCopy.to_dt.setMilliseconds(0);
          transactionCopy.to_dt = this.timezoneService.convertToUtc(transactionCopy.to_dt, localeOffset);
        }
        if (transactionCopy.from_dt) {
          transactionCopy.from_dt.setHours(12);
          transactionCopy.from_dt.setMinutes(0);
          transactionCopy.from_dt.setSeconds(0);
          transactionCopy.from_dt.setMilliseconds(0);
          transactionCopy.from_dt = this.timezoneService.convertToUtc(transactionCopy.from_dt, localeOffset);
        }
        return this.post('/duplicate/test', transactionCopy);
      })
    );
  }
Example #20
Source File: index.ts    From gant-design with MIT License 6 votes vote down vote up
getPureData() {
    const data: any[] = [];
    if (!this.agGridApi) return data;
    this.agGridApi.forEachNode(function(node, index) {
      let cloneData = cloneDeep(get(node, 'data', {}));
      if (!isEmpty(cloneData)) {
        const { _rowType, _rowData, _rowCut, _rowError, ...itemData } = cloneData;
        if (_rowType !== DataActions.removeTag) data.push({ ...itemData, dataNumber: index });
      }
    } as any);
    return data;
  }
Example #21
Source File: QueryBuilderComponent.tsx    From druid-grafana with Apache License 2.0 6 votes vote down vote up
useScopedQueryBuilderProps = (
  props: QueryBuilderProps,
  component: QueryBuilderComponent<QueryComponent | Component>
) => {
  const builder = initBuilder(props.options.builder || {}, component);
  return (name: string | undefined, scopeType: ScopeType = ScopeType.Builder): QueryBuilderProps => {
    if (name === undefined) {
      name = '';
    }
    let scopedProps = cloneDeep(props);
    scopedProps.options.builder = name in builder ? builder[name] : undefined;
    scopedProps.onOptionsChange = (options: QueryBuilderOptions) => {
      let newBuilder: any = {};
      if (name === undefined) {
        name = '';
      }
      if (name in builder) {
        newBuilder = { ...builder, [name]: options.builder };
      } else {
        newBuilder = { ...builder, ...options.builder };
      }
      let newOptions = { ...options, builder: newBuilder };
      props.onOptionsChange(newOptions);
    };
    return scopedProps;
  };
}
Example #22
Source File: GetName.ts    From alchemist with MIT License 6 votes vote down vote up
export function getName(refs: TReference[]): IGetNameOutput[] {
	const copyRef = cloneDeep(refs);
	const nameParts:IGetNameOutput[] = [];

	while (copyRef.length) {
		if ("_property" in copyRef[0]) {
			nameParts.push({ typeRef: "property", value: copyRef[0]._property, typeTitle: "PR" });
		} else if ("_ref" in copyRef[0]) {
			nameParts.push({
				typeRef: copyRef[0]._ref,
				typeTitle:getTypeTitle(copyRef[0]._ref),
				value: getNameProp(copyRef),
			});
		}
		
		copyRef.shift();
	}
	
	return nameParts.reverse();
}
Example #23
Source File: gamelogic.ts    From sc2-planner with MIT License 5 votes vote down vote up
exportSettings(): ISettingsElement[] {
        // Update default settings from gamelogic.settings object, then return it
        const settingsObject = cloneDeep(defaultSettings)
        settingsObject.forEach((item) => {
            item.v = this.settings[item.variableName]
        })
        return settingsObject
    }
Example #24
Source File: BaseChart.ts    From anichart.js with MIT License 5 votes vote down vote up
setData() {
    this.data = cloneDeep(recourse.data.get(this.dataName));
    let dateSet = new Set();
    let dateIndex = 0;
    this.indexToDate = new Map<number, string>();
    this.data.forEach((d: any) => {
      if (!dateSet.has(d[this.dateField])) {
        dateSet.add(d[this.dateField]);
        dateIndex += 1;
        this.indexToDate.set(dateIndex, d[this.dateField]);
      }
      Object.keys(d).forEach((k) => {
        switch (k) {
          case this.dateField:
            // 日期字符串转成日期
            let date = moment(d[this.dateField]).toDate();
            if (isValidDate(date)) {
              d[k] = date;
              this.nonstandardDate = false;
            } else {
              this.nonstandardDate = true;
              d[k] = new Date(dateIndex);
            }
            break;
          case this.idField:
            // ID保持不变
            break;
          default:
            // 数值转成数字
            if (
              typeof d[k] === "string" &&
              (this.valueKeys.includes(k) || this.valueField === k)
            ) {
              d[k] = +d[k].replace(/,/g, "");
            }
        }
      });
    });
    this.dataGroupByID = group(this.data, (d) => d[this.idField]);
    const dataGroupByDate = group(this.data, (d) =>
      (d[this.dateField] as Date).getTime()
    );
    const result = new Map<Date, any>();
    dataGroupByDate.forEach((v: any[], k: number) => {
      result.set(new Date(k), v);
    });
    this.dataGroupByDate = result;
  }
Example #25
Source File: app.reducer.ts    From nica-os with MIT License 5 votes vote down vote up
_appReducer = createReducer(initialState,
  on(loadAssets, (state) => ({...state, loading: true})),
  on(loadAssetsSuccess, (state, {loadedAssets}) => ({...state, loadedAssets, loading: false})),
  on(setLoadingMessage, (state, {message}) => ({...state, loadingMessage: [...state.loadingMessage, message]})),
  on(setConsoleMessage, (state, {message}) => ({...state, consoleMessages: [...state.consoleMessages, message]})),
  on(toggleMenuActive, (state) => ({...state, menuActive: !state.menuActive})),
  on(closeMenu, (state) => ({...state, menuActive: false})),
  on(createApp, (state, {app, data}) => {
    const applications = cloneDeep(state.applications);
    let newApp = cloneDeep(app);
    applications.map(a => {
      a.properties.focus = newApp ? a.id === newApp.id : false;
      /** if there is at least one focused app there is no new app */
      if ( a.properties.focus ) {
        a.properties.minified = false;
        newApp = null;
      }
    });
    if ( newApp ) {
      applications.push(newApp);
      if ( data ) { newApp.properties.data = data; }
    }
    return {...state, applications};
  }),
  on(closeApp, (state, {app}) => {
    let applications = cloneDeep(state.applications);
    applications = applications.filter(w => w.id !== app.id);
    return {...state, applications};
  }),
  on(setAppFullscreen, (state, {app, fullScreen}) => {
    const applications = cloneDeep(state.applications);
    applications.map(w => w.id === app.id ? w.properties.fullScreen = fullScreen : w);
    return {...state, applications};
  }),
  on(setAppFocus, (state, {app, focus}) => {
    const applications = cloneDeep(state.applications);
    applications.map(w => w.id === app.id ? w.properties.focus = focus : w.properties.focus = false);
    return {...state, applications, menuActive: false};
  }),
  on(setAppMinified, (state, {app, minified}) => {
    const applications = cloneDeep(state.applications);
    applications.map(w => w.id === app.id ? w.properties.minified = minified : w);
    return {...state, applications};
  }),
  on(setTheme, (state, {theme}) => ({...state, appSettings: {...state.appSettings, theme}})),
  on(toggleTaskbarThemeSelector, (state) => ({
    ...state,
    taskbarThemeSelectorActive: !state.taskbarThemeSelectorActive
  })),
)
Example #26
Source File: scan-code.service.ts    From barista with Apache License 2.0 5 votes vote down vote up
async extractLicenseInformation(json: any, pathToMatch: string) {
    return new Promise<any>((resolve, reject) => {
      const fileKey = 'files';

      of(json[fileKey])
        .pipe(
          first(),
          map((items: any[]) => {
            return items
              .map((item: any) => {
                if (item.path.indexOf(pathToMatch)===-1) {
                  return [];
                }

                let licenses=[];
                if (item.licenses) {
                  // Let's invert the license/file so that each license will have a reference to it's file
                  // so we can report it later

                  licenses = item.licenses.filter((license:any) => {return license.key !== "unknown-license-reference" && license.key !== "proprietary-license";});

                  licenses.forEach(license => {
                    const file = cloneDeep(item);
                    delete file.licenses;
                    license.file = file;
                  });
                }
                return licenses;
              })
              .reduce((previousValue: any[], currentValue: any[], currentIndex: number, array: any[]) => {
                if (currentValue.length > 0) {
                  const result = [...previousValue, ...currentValue];
                  return result;
                } else {
                  return [...previousValue];
                }
              });
          }),
        )
        .subscribe(
          result => {
            resolve(result);
          },
          error => {
            reject(error);
          },
        );
    });
  }
Example #27
Source File: settings.ts    From ui5-language-assistant with Apache License 2.0 5 votes vote down vote up
export function setGlobalSettings(settings: Settings): void {
  globalSettings = cloneDeep(settings);
  deepFreezeStrict(globalSettings);
}
Example #28
Source File: platform.ts    From HomebridgeMagicHome-DynamicPlatform with Apache License 2.0 5 votes vote down vote up
//send

  static isValidDeviceModel(_device: IDeviceProps, logger): boolean {
    const device = cloneDeep(_device);
    try {
      const { lightParameters } = device || {};

      const rootProps = ['UUID', 'cachedIPAddress', 'restartsSinceSeen', 'displayName', 'ipAddress', 'uniqueId', 'modelNumber', 'lightParameters', 'controllerHardwareVersion', 'controllerFirmwareVersion'];
      const lightProps = ['controllerLogicType', 'convenientName', 'simultaneousCCT', 'hasColor', 'hasBrightness'];

      const missingRootProps = rootProps.filter(k => device[k] === undefined || device[k] == null);
      const missingLightProps = lightProps.filter(k => lightParameters[k] === undefined || lightParameters[k] == null);

      const missingProps = [...missingRootProps, ...missingLightProps];

      // special case: props that can be null: 'lastKnownState'
      if (device.lastKnownState === undefined) {
        missingProps.push('lastKnownState');
      }

      if (!Object.values(ControllerTypes).includes(lightParameters.controllerLogicType)) {
        if (logger) {
          logger.error(`[isValidDeviceModel] The ContollerLogicType "${lightParameters.controllerLogicType}" is unknown.`);
        }
        return false;
      }


      if (missingProps.length > 0) {
        if (logger) {
          logger.error('[isValidDeviceModel] unable to validate device model. Missing properties: ', missingProps);
          logger.debug('\nThree things are certain:\nDeath, taxes and lost data.\nGuess which has occurred.');
        }
        return false;
      }

      return true;
    } catch (err) {
      return false;
    }

  }
Example #29
Source File: issue-507-spec.ts    From S2 with MIT License 5 votes vote down vote up
valueInRows = cloneDeep(valueInCols)