lodash#forEach TypeScript Examples

The following examples show how to use lodash#forEach. 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: util.ts    From redux-with-domain with MIT License 7 votes vote down vote up
export function parseActionsAndReducers(
  namespace: string,
  reducerMap,
  moduleType
) {
  const actions = {}
  const reducers = {}
  forEach(reducerMap, (reducer, actionType) => {
    const actionTypeWithNamespace = getActionTypeWithNamespace(
      namespace,
      actionType
    )
    reducers[actionTypeWithNamespace] = reducer
    actions[actionType] = createAction({
      namespace,
      actionType,
      moduleType,
      actionKind: ACTION_KIND.REDUCER
    })
  })

  return {
    actions,
    reducers
  }
}
Example #2
Source File: completion-items-utils.ts    From ui5-language-assistant with Apache License 2.0 7 votes vote down vote up
/** Check the suggestions will be displayed to the user according to the range and filter text */
function assertSuggestionsAreValid(
  suggestions: CompletionItem[],
  xmlSnippet: string
): void {
  const { document, position } = getXmlSnippetDocument(xmlSnippet);
  forEach(suggestions, (suggestion) => {
    expectExists(suggestion.textEdit, "suggestion contains a textEdit");
    assertRangeContains(suggestion.textEdit.range, position, suggestion.label);
    assertRangesDoNotOverlap(
      document,
      suggestion.label,
      suggestion.textEdit,
      suggestion.additionalTextEdits || []
    );
    // The filter text is checked until the position in the document
    // (for example, we can replace "Ab⇶cd" with "Abzzz" even though "c" and "d" aren't in "Abzzz")
    const checkedRange = {
      start: suggestion.textEdit?.range.start,
      end: position,
    };
    assertFilterMatches(
      suggestion.filterText ?? suggestion.label,
      document.getText(checkedRange),
      suggestion.label
    );
  });
}
Example #3
Source File: utils.ts    From yforms with MIT License 7 votes vote down vote up
export function submitFormatValues(
  values: KeyValue,
  formatFieldsValue?: FormatFieldsValue[],
): KeyValue {
  const _values = mergeWithDom({}, values);
  const list: FormatFieldsValue[] = sortBy(formatFieldsValue, (item) => {
    if (!item) return;
    if (isArray(item.name)) {
      return -item.name.length;
    }
    return -`${item.name}`.length;
  }).filter((x) => x);
  forEach(list, (item) => {
    const { name, format } = item;
    if (name && format) {
      const parentValue = getParentNameData(values, name);
      // 如果上一级是 undefined,则不处理该字段。(List add 会生成空对象)
      if (parentValue === undefined) return;
      try {
        set(_values, name, format(get(values, name), parentValue, values));
      } catch (error) {
        // 如果 format 代码报错这里抛出异常
        // eslint-disable-next-line no-console
        console.error(error);
        warning(false, error);
      }
    }
  });
  return _values;
}
Example #4
Source File: utils.ts    From next-basics with GNU General Public License v3.0 7 votes vote down vote up
safeDumpFields = (
  values: Record<string, any>
): Record<string, string> => {
  const result = { ...values };
  forEach(values, (originValue, field) => {
    result[field] = safeDumpField(originValue, field);
  });
  return result;
}
Example #5
Source File: yml-flow-util.ts    From erda-ui with GNU Affero General Public License v3.0 7 votes vote down vote up
clearNullFromArray = (array: any[]) => {
  const deleteItems: number[] = [];
  array.forEach((i: any, index: number) => {
    if (typeof i === 'object') {
      const keys: string[] = Object.keys(i);
      let deleteCount = 0;
      keys.forEach((key: string) => {
        if (!i[key]) {
          deleteCount += 1;
          // eslint-disable-next-line no-param-reassign
          delete i[key];
        } else if (i[key] instanceof Array) {
          // eslint-disable-next-line no-param-reassign
          i[key] = clearNullFromArray(i[key]);
        } else if (typeof i[key] === 'object') {
          clearNullValue(i[key]);
        }
      });
      if (deleteCount === keys.length) {
        deleteItems.push(index);
      }
    }
  });

  return array.filter((_i: any, index: number) => !deleteItems.includes(index));
}
Example #6
Source File: server.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
connection.onDidChangeWatchedFiles(async (changeEvent) => {
  getLogger().debug("`onDidChangeWatchedFiles` event", { changeEvent });
  forEach(changeEvent.changes, async (change) => {
    const uri = change.uri;
    if (!isManifestDoc(uri)) {
      return;
    }
    await updateManifestData(uri, change.type);
  });
});
Example #7
Source File: CreateAppFromExcel.tsx    From amplication with Apache License 2.0 6 votes vote down vote up
function getColumnSampleData(
  data: WorksheetData,
  maxCount: number,
  columnKey: number
): unknown[] {
  const results: unknown[] = [];
  forEach(data, function (row) {
    if (results.length === maxCount) {
      return false;
    }
    if (undefined !== row[columnKey]) {
      results.push(row[columnKey]);
    }
  });
  return results;
}
Example #8
Source File: header-cell.ts    From S2 with MIT License 6 votes vote down vote up
protected drawActionIcons() {
    if (this.showSortIcon()) {
      this.drawSortIcons();
      return;
    }

    const actionIconCfg = this.getActionIconCfg();
    if (!actionIconCfg) {
      return;
    }

    const { iconNames, action, defaultHide } = actionIconCfg;

    const position = this.getIconPosition(iconNames.length);

    const { size, margin } = this.getStyle().icon;
    forEach(iconNames, (iconName, i) => {
      const x = position.x + i * size + i * margin.left;
      const y = position.y;
      this.addActionIcon({ iconName, x, y, defaultHide, action });
    });
  }
Example #9
Source File: organizations.seeder.ts    From nestjs-rest-microservices with MIT License 6 votes vote down vote up
async seedDatabase(): Promise<number> {
    const recordCount: number = await this.service.count()

    if (recordCount > 0) {
      this.logger.info('OrganizationsSeeder#seedDatabase', 'Aborting...')

      return recordCount
    }

    forEach(this.ORGS, async id => {
      const organization: Organization = await this.service.create({
        id,
        name: helpers.slugify(company.companyName(1))
      })

      this.logger.info('OrganizationsSeeder#seedDatabase.newRecord', organization)
    })

    return this.ORGS.length
  }
Example #10
Source File: ItemsTypeModify.tsx    From yforms with MIT License 6 votes vote down vote up
checkboxGroupModify: YFormFieldBaseProps<YCheckGroupProps>['modifyProps'] = ({
  itemProps,
  componentProps,
}) => {
  const { options } = componentProps;
  return {
    itemProps: {
      viewProps: {
        format: (value, pureValue) => {
          if (value && isArray(value)) {
            const list = [];
            forEach(options, (item) => {
              if (includes(value, item.id)) {
                list.push(item.name);
              }
            });
            if (pureValue) {
              if (isArray(value)) {
                return map(value, (item) => item).join('-');
              }
              return value;
            }
            return map(list, (item, index) => <Tag key={index}>{item}</Tag>);
          }
        },
      },
      ...itemProps,
    },
  };
}
Example #11
Source File: index.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
// istanbul ignore next
  private initData(mutableProps: {
    mainTitle: string;
    description: string;
    subTitle: string;
  }): void {
    const pickFields = pick(this.fields, [
      "mainTitle",
      "description",
      "subTitle",
    ]);
    forEach(pickFields, (fieldKey, field: string) => {
      set(mutableProps, field, get(this.dataSource, fieldKey));
    });
  }
Example #12
Source File: get-profiles-from-response.spec.ts    From linkedin-private-api with MIT License 6 votes vote down vote up
test('should pull mini profiles out of response', () => {
  const response = createResponse(10);
  const profiles = getProfilesFromResponse(response);

  expect(size(profiles)).toEqual(10);
  forEach(profiles, profile => {
    expect(Object.keys(profile).sort()).toEqual(Object.keys(Object.values(profiles)[0]).sort());
  });
});
Example #13
Source File: index.ts    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
extractPathParams = (path: string, params?: Obj<any>) => {
  const keys: Key[] = [];
  pathToRegexp(path, keys);
  const pathParams = {} as Obj<string>;
  const bodyOrQuery = { ...params };
  if (keys.length > 0) {
    keys.forEach(({ name }) => {
      pathParams[name] = bodyOrQuery[name];
      delete bodyOrQuery[name];
    });
  }
  return {
    pathParams,
    bodyOrQuery,
  };
}
Example #14
Source File: I18nProvider.tsx    From mo360-ftk with MIT License 6 votes vote down vote up
function createTranslationRegistry(translationMap: ITranslationMap) {
  const registry = new Registry<ITranslation>();
  const translations = TranslationMap.convert(translationMap);
  forEach(translations, (translation) => {
    registry.add(translation.translationId, translation);
  });

  return registry;
}
Example #15
Source File: list.monad.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
/**
     * Iterate over each item in the List, without modifying value
     * @param   project   callback invoked for each item
     * ```ts
     * const start = List.from([1,2,3])
     * const end = start.forEach((v) => v+1);
     * end.toArray() // [1,2,3]
     * ```
     */
    forEach(project: (val: T) => void): this {
        forEach([...this], project);

        return this;
    }
Example #16
Source File: action.ts    From redux-with-domain with MIT License 5 votes vote down vote up
export function createActionCreators({
  namespace,
  module,
  actionCreators,
  moduleType,
  checkAuth
}) {
  const actions = {}

  const createActionWarpper = (type: string) => {
    return createAction({
      namespace,
      actionType: type,
      actionKind: ACTION_KIND.CREATOR,
      moduleType
    })
  }

  let dispatch

  // wrap dispatch for layered call auth check
  if (process.env.NODE_ENV === 'development') {
    dispatch = (action: any) => {
      checkAuth(action, namespace)
      return window[KOP_GLOBAL_STORE_REF].dispatch(action)
    }
  } else {
    dispatch = window[KOP_GLOBAL_STORE_REF].dispatch
  }

  const moduleActionCreators = actionCreators({
    actions: module.actions,
    selectors: module.selectors,
    createAction: createActionWarpper, // helper for create plain action creator
    dispatch
  })

  forEach({ ...moduleActionCreators }, (creator, type) => {
    invariant(
      !module.actions[type],
      `Module ${namespace} action ${type} duplicated`
    )

    // wrap actionCreator to add meta data for the returned action
    if (process.env.NODE_ENV === 'development') {
      actions[type] = actionCreatorWithMetaTag(
        creator,
        namespace,
        moduleType,
        type
      )
    } else {
      actions[type] = creator // directly pass in user defined actionCreator on module.actions
    }
  })

  return {
    actionCreators: actions
  }
}
Example #17
Source File: find-classes-matching-spec.ts    From ui5-language-assistant with Apache License 2.0 5 votes vote down vote up
describe("The @ui5-language-assistant/logic-utils <findClassesMatchingType> function", () => {
  let ui5Model: UI5SemanticModel;
  before(async () => {
    ui5Model = await generateModel({
      version: "1.74.0",
      modelGenerator: generate,
    });
  });

  it("can locate classes matching an interface directly", () => {
    const targetInterface = ui5Model.interfaces["sap.m.IconTab"];
    const matchingClasses = findClassesMatchingType({
      type: targetInterface,
      model: ui5Model,
    });
    const matchingClassesNames = map(matchingClasses, ui5NodeToFQN);
    expect(matchingClassesNames).to.deep.equalInAnyOrder([
      "sap.m.IconTabFilter",
      "sap.m.IconTabSeparator",
    ]);
  });

  it("can locate classes matching an interface transitively", () => {
    const expectedTransitiveMatches = [
      ui5Model.classes["sap.tnt.ToolHeader"],
      ui5Model.classes["sap.uxap.AnchorBar"],
    ];
    const targetInterface = ui5Model.interfaces["sap.m.IBar"];
    forEach(expectedTransitiveMatches, (_) => {
      expect(
        _.implements,
        `A matching **direct** implements clause found!`
      ).to.not.include.members([targetInterface]);
    });

    const matchingClasses = findClassesMatchingType({
      type: targetInterface,
      model: ui5Model,
    });
    expect(matchingClasses).to.include.members(expectedTransitiveMatches);
  });

  it("can locate classes matching another Class", () => {
    const targetClassType = ui5Model.classes["sap.m.ListBase"];
    const matchingClasses = findClassesMatchingType({
      type: targetClassType,
      model: ui5Model,
    });
    const matchingClassesNames = map(matchingClasses, ui5NodeToFQN);
    expect(matchingClassesNames).to.deep.equalInAnyOrder([
      "sap.f.GridList",
      "sap.m.FacetFilterList",
      "sap.m.GrowingList",
      "sap.m.List",
      "sap.m.ListBase",
      "sap.m.Table",
      "sap.m.Tree",
      "sap.ca.ui.Notes",
    ]);
  });
});
Example #18
Source File: custom-tree-pivot-data-set.ts    From S2 with MIT License 5 votes vote down vote up
processDataCfg(dataCfg: S2DataConfig): S2DataConfig {
    // 自定义行头有如下几个特点
    // 1、rows配置必须是空,需要额外添加 $$extra$$ 定位数据(标记指标的id)
    // 2、要有配置 fields.rowCustomTree(行头结构)
    // 3、values 不需要参与计算,默认就在行头结构中
    dataCfg.fields.rows = [EXTRA_FIELD];
    dataCfg.fields.valueInCols = false;
    const { data, ...restCfg } = dataCfg;
    const { values } = dataCfg.fields;
    // 将源数据中的value值,映射为 $$extra$$,$$value$$
    // {
    // province: '四川',    province: '四川',
    // city: '成都',   =>   city: '成都',
    // price='11'           price='11'
    //                      $$extra$$=price
    //                      $$value$$=11
    // 此时 province, city 均配置在columns里面
    // }
    const transformedData = [];
    forEach(data, (dataItem) => {
      if (isEmpty(intersection(keys(dataItem), values))) {
        transformedData.push(dataItem);
      } else {
        forEach(values, (value) => {
          if (has(dataItem, value)) {
            transformedData.push({
              ...dataItem,
              [EXTRA_FIELD]: value,
              [VALUE_FIELD]: dataItem[value],
            });
          }
        });
      }
    });

    return {
      data: uniq(transformedData),
      ...restCfg,
    };
  }