lodash#map TypeScript Examples

The following examples show how to use lodash#map. 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: utils.ts    From prism-frontend with MIT License 7 votes vote down vote up
function formatLayersCategories(layersList: {
  [key: string]: Array<LayerKey | TableKey>;
}): LayersCategoriesType {
  return map(layersList, (layerKeys, layersListKey) => {
    return {
      title: startCase(layersListKey),
      layers: layerKeys.filter(isLayerKey).map(key => {
        if (typeof key === 'object') {
          const group = (mapKeys(key, (_v, k: string) =>
            camelCase(k),
          ) as unknown) as MenuGroup;
          const mainLayer = group.layers.find(l => l.main);
          const layer = LayerDefinitions[mainLayer?.id as LayerKey];
          // eslint-disable-next-line fp/no-mutation
          layer.group = group;
          return layer;
        }
        return LayerDefinitions[key as LayerKey];
      }),
      tables: layerKeys.filter(isTableKey).map(key => TableDefinitions[key]),
    };
  });
}
Example #2
Source File: util.ts    From S2 with MIT License 7 votes vote down vote up
checkItem = (
  source: SwitcherItem[] = [],
  checked: boolean,
  id: string,
  parentId?: string,
): SwitcherItem[] => {
  const target: SwitcherItem = {
    ...source.find((item) => item.id === (parentId ?? id)),
  };

  // 有 parentId 时,说明是第二层级的改变
  if (parentId) {
    target.children = map(target.children, (item) => ({
      ...item,
      checked: item.id === id ? checked : item.checked,
    }));
  } else {
    target.checked = checked;
    target.children = map(target.children, (item) => ({
      ...item,
      checked,
    }));
  }

  return source.map((item) => (item.id === target.id ? target : item));
}
Example #3
Source File: utils.ts    From aqualink-app with MIT License 7 votes vote down vote up
convertDailyToSofar = (
  dailyData?: DailyData[],
  metrics?: Exclude<keyof DailyData, "id" | "date">[]
):
  | Partial<
      Record<Exclude<keyof DailyData, "id" | "date">, ValueWithTimestamp[]>
    >
  | undefined => {
  const sortedData = sortByDate(dailyData || [], "date");

  return metrics?.reduce(
    (acc, metric) => ({
      ...acc,
      [metric]: sortedData.map((item) => ({
        value: item[metric],
        timestamp: item.date,
      })),
    }),
    {}
  );
}
Example #4
Source File: query.utils.ts    From nestjs-rest-microservices with MIT License 7 votes vote down vote up
async getOrder(orderBy: string): Promise<Array<Array<string>>> {
    let result: Array<Array<string>> = []

    if (!isEmpty(orderBy)) {
      const attributes: Array<string> = orderBy.split(',')

      result = map(attributes, attribute => {
        if (attribute.trim().charAt(0) === '-') {
          return [attribute.trim().substr(1), 'DESC']
        }
        return [attribute.trim(), 'ASC']
      })
    }

    return result
  }
Example #5
Source File: utils.ts    From yforms with MIT License 7 votes vote down vote up
searchSelect = {
  allowClear: true,
  showSearch: true,
  optionFilterProp: 'children',
  filterOption: (input: string, option: any) => {
    const getValue = (dom: React.ReactNode): string => {
      const _value = get(dom, 'props.children');
      if (Array.isArray(_value)) {
        const d = map(_value, (item) => {
          if (isValidElement(item)) {
            return getValue(item);
          }
          return item;
        });
        return join(d, '');
      }
      if (isValidElement(_value)) {
        return getValue(_value);
      }
      return join(_value, '');
    };

    const str = getValue(option);
    return str.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  },
}
Example #6
Source File: utils.tsx    From erda-ui with GNU Affero General Public License v3.0 7 votes vote down vote up
createTabsField = ({
  tabs,
  customProps,
  name,
}: {
  name: string;
  tabs: Array<{ tab: string; fields: Field[] }>;
  customProps: IFormTabProps;
}): Field => {
  const tabsProperties: Field[] = (tabs ?? []).map((tabItem) => {
    const { tab, fields } = tabItem;
    return {
      type: 'void',
      component: FormTab.TabPane,
      componentName: 'ErdaTabPane',
      name: tab,
      customProps: {
        tab,
      },
      properties: fields,
    };
  }, []);
  const result = {
    type: 'void',
    component: FormTab,
    name,
    customProps: {
      ...customProps,
      formTab: FormTab.createFormTab!(),
    },
    noPropertyLayoutWrapper: true,
    properties: tabsProperties,
  };
  return result;
}
Example #7
Source File: completion-items.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
function transformToLspSuggestions(
  suggestions: UI5XMLViewCompletion[],
  model: UI5SemanticModel,
  textDocumentPosition: TextDocumentPositionParams
): CompletionItem[] {
  const lspSuggestions = map(suggestions, (suggestion) => {
    const lspKind = computeLSPKind(suggestion);

    const textEditDetails = createTextEdits(
      suggestion,
      textDocumentPosition.position
    );
    const documentation = getDocumentation(suggestion, model);
    const completionItem: CompletionItem = {
      label: getLabel(suggestion),
      filterText: textEditDetails.filterText,
      textEdit: textEditDetails.textEdit,
      insertTextFormat: InsertTextFormat.Snippet,
      additionalTextEdits: textEditDetails.additionalTextEdits,
      detail: getDetail(suggestion),
      documentation: documentation,
      kind: lspKind,
      // TODO tags are not supported in Theia: https://che-incubator.github.io/vscode-theia-comparator/status.html
      // tags: suggestion.ui5Node.deprecatedInfo?.isDeprecated
      //   ? [CompletionItemTag.Deprecated]
      //   : undefined
    };
    return completionItem;
  });
  return lspSuggestions;
}
Example #8
Source File: AirportLayer.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
export function AirportLayer(props: AirportLayerProps) {
  const { airports } = props;

  return (
    <React.Fragment>
      {map(airports, (airport, i) => (
        <AirportMarker key={`airports${airport}${i}`} airport={airport} />
      ))}
    </React.Fragment>
  );
}
Example #9
Source File: header-cell.ts    From S2 with MIT License 6 votes vote down vote up
protected handleSelect(cells: CellMeta[], nodes: Node[]) {
    if (includeCell(cells, this)) {
      this.updateByState(InteractionStateName.SELECTED);
    }
    const selectedNodeIds = map(nodes, 'id');
    if (includes(selectedNodeIds, this.meta.id)) {
      this.updateByState(InteractionStateName.SELECTED);
    }
  }
Example #10
Source File: utils.ts    From aqualink-app with MIT License 6 votes vote down vote up
getSurveyDates = (surveys: SurveyListItem[]): number[] =>
  surveys
    .filter(({ diveDate }) => !isNil(diveDate))
    .map(({ diveDate }) => new Date(diveDate as string).setHours(0, 0, 0, 0))
Example #11
Source File: index.tsx    From brick-design with MIT License 6 votes vote down vote up
/**
 * 渲染分类组件中的组件
 * @param categoryInfo  分类信息
 * @param categoryName  分分类名字
 * @param isShow        是否展示分割分类组件名
 */
function renderContent(categoryInfo: ComponentInfoType, categoryName: string) {
  let items: any = null;
  if (!categoryInfo || isEmpty(categoryInfo.props || categoryInfo.components)) {
    items = renderDragItem(undefined, categoryName);
  } else {
    const { props, components } = categoryInfo;
    const renderItems = props || components;
    items = map(renderItems, (v: ComponentCategoryType | any, k) => {
      return renderDragItem(k, isNaN(Number(k)) ? k : categoryName, v);
    });
  }

  return (
    <div key={categoryName} className={styles['fold-content']}>
      {items}
    </div>
  );
}
Example #12
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 #13
Source File: index.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
connectedCallback(): void {
    if (!isEmpty(this.hotkeysConfig)) {
      hotkeys.filter = function (event) {
        return true;
      };
      hotkeys(map(this.hotkeysConfig, "key").join(","), (event, handler) => {
        event.preventDefault();
        const found = find(this.hotkeysConfig, ["key", handler.key]);
        if (found?.eventName) {
          if (!this.disabled) {
            this.dispatchEvent(new CustomEvent(found.eventName));
          }
        }
      });
    }
  }
Example #14
Source File: conversation.repository.ts    From linkedin-private-api with MIT License 6 votes vote down vote up
transformConversations = ({
  conversations,
  profiles,
}: {
  conversations: LinkedinConversation[];
  profiles: Record<ProfileId, MiniProfile>;
}): Conversation[] =>
  conversations.map(conversation => {
    const participants = map(conversation['*participants'], participant => {
      const profileId = participantToProfileId(participant);

      return profiles[profileId];
    }) as MiniProfile[];

    return {
      ...conversation,
      participants,
      conversationId: transformConversationId(conversation.entityUrn),
    };
  })
Example #15
Source File: regist-router.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
resetRouter = (routers: Obj<SHELL.Route[]>) => {
  return produce(routers, (draft) => {
    const routerMarkObj: Obj = {};
    const toMarkObj: Obj = {};
    const getRouterMarks = (_r: SHELL.Route[], _path: string) => {
      _r.forEach((rItem: SHELL.Route, idx: number) => {
        const { mark, routes: _rs, toMark } = rItem;
        if (mark && !routerMarkObj[mark]) {
          routerMarkObj[mark] = rItem;
        }
        if (toMark) {
          toMarkObj[toMark] = (toMarkObj[toMark] || []).concat({ router: rItem, key: `${_path}.[${idx}]` });
        }

        if (_rs) {
          getRouterMarks(_rs, `${_path}.[${idx}].routes`);
        }
      });
    };

    map(draft, (rItem, key) => {
      getRouterMarks(rItem, key);
    });

    map(toMarkObj, (_toObjArr, k) => {
      map(_toObjArr, (_toObj) => {
        const { key, router: _toRouter } = _toObj;
        if (_toRouter && routerMarkObj[k]) {
          _toRouter.toMark = undefined;
          routerMarkObj[k].routes = (routerMarkObj[k].routes || []).concat(_toRouter);
          set(draft, key, undefined);
        }
      });
    });
  });
}
Example #16
Source File: quick-fix.ts    From ui5-language-assistant with Apache License 2.0 5 votes vote down vote up
function computeCodeActionsForQuickFixFileStableId(opts: {
  document: TextDocument;
  xmlDocument: XMLDocument;
  ui5Model: UI5SemanticModel;
}): CodeAction[] {
  const actualValidators = {
    document: [],
    element: [validators.validateNonStableId],
    attribute: [],
  };

  // We re-validate intentionally to keep the flow simple & stateless
  const nonStableIdFileIssues = validateXMLView({
    validators: actualValidators,
    model: opts.ui5Model,
    xmlView: opts.xmlDocument,
  });

  // We don't suggest quick fix stabel stable id for entire file when there is only one non-stable id issue
  if (nonStableIdFileIssues.length === 1) {
    return [];
  }

  const errorsOffset = map(nonStableIdFileIssues, (_) => _.offsetRange);
  const nonStableIdFileIssuesInfo = computeQuickFixStableIdInfo(
    opts.xmlDocument,
    errorsOffset
  );
  const nonStableIdFileIssuesLSPInfo: QuickFixStableIdLSPInfo[] = map(
    nonStableIdFileIssuesInfo,
    (_) => ({
      newText: _.newText,
      replaceRange: offsetRangeToLSPRange(_.replaceRange, opts.document),
    })
  );

  return [
    CodeAction.create(
      commands.QUICK_FIX_STABLE_ID_FILE_ERRORS.title,
      Command.create(
        commands.QUICK_FIX_STABLE_ID_FILE_ERRORS.title,
        commands.QUICK_FIX_STABLE_ID_FILE_ERRORS.name,
        opts.document,
        opts.document.uri,
        opts.document.version,
        nonStableIdFileIssuesLSPInfo
      ),
      CodeActionKind.QuickFix
    ),
  ];
}