lodash#findLast TypeScript Examples

The following examples show how to use lodash#findLast. 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: data-cell.ts    From S2 with MIT License 6 votes vote down vote up
/**
   * Find current field related condition
   * @param conditions
   */
  protected findFieldCondition(conditions: Condition[]): Condition {
    return findLast(conditions, (item) => {
      return item.field instanceof RegExp
        ? item.field.test(this.meta.valueField)
        : item.field === this.meta.valueField;
    });
  }
Example #2
Source File: turn.ts    From fishbowl with MIT License 6 votes vote down vote up
export function nextPlayerForNextTeam(
  activePlayer: CurrentGameSubscription["games"][0]["players"][0] | null,
  turns: CurrentGameSubscription["games"][0]["turns"],
  players: CurrentGameSubscription["games"][0]["players"]
) {
  if (!activePlayer) {
    return sortBy(players, ["team_sequence"])[0]
  }
  const lastTeamToPlay = activePlayer.team
  const nextTeamToPlay = lastTeamToPlay === Team.Blue ? Team.Red : Team.Blue
  const nextTeamToPlayPlayers = filter(
    players,
    (player) => player.team === nextTeamToPlay
  )
  const lastTurnFromNextTeamToPlay = findLast(turns, (turn) =>
    nextTeamToPlayPlayers.map((player) => player.id).includes(turn.player_id)
  )
  const lastPlayerFromNextTeamToPlay = lastTurnFromNextTeamToPlay
    ? players.find(
        (player) => player.id === lastTurnFromNextTeamToPlay.player_id
      )
    : null

  const nextTeamPlayersSortedBySequence = sortBy(nextTeamToPlayPlayers, [
    "team_sequence",
  ])
  const nextPlayerFromNextTeamToPlay = lastPlayerFromNextTeamToPlay
    ? nextTeamPlayersSortedBySequence[
        ((lastPlayerFromNextTeamToPlay.team_sequence || 0) + 1) %
          nextTeamToPlayPlayers.length
      ]
    : nextTeamPlayersSortedBySequence[0]

  return nextPlayerFromNextTeamToPlay
}
Example #3
Source File: txInterpreter.ts    From nautilus-wallet with MIT License 6 votes vote down vote up
constructor(tx: UnsignedTx, ownAddresses: string[], assetInfo: StateAssetInfo) {
    this._tx = tx;
    this._addresses = ownAddresses;
    this._assetInfo = assetInfo;
    this._feeBox = find(tx.outputs, (b) => b.ergoTree === MINER_FEE_TREE);
    this._changeBox = findLast(tx.outputs, (b) =>
      ownAddresses.includes(addressFromErgoTree(b.ergoTree))
    );
    this._sendingBoxes = difference(tx.outputs, [this._feeBox, this._changeBox]).filter(
      (b) => b !== undefined
    ) as ErgoBoxCandidate[];

    if (isEmpty(this._sendingBoxes) && this._changeBox) {
      this._sendingBoxes.push(this._changeBox);
      this._changeBox = undefined;
    }
  }
Example #4
Source File: roam-vim-panel.ts    From roam-toolkit with MIT License 5 votes vote down vote up
private lastVisibleBlock() {
        return assumeExists(findLast(this.blocks(), blockIsVisible), 'Could not find any visible block')
    }
Example #5
Source File: pipeline-node.tsx    From erda-ui with GNU Affero General Public License v3.0 4 votes vote down vote up
render() {
    const { time } = this.state;
    const { item, className, onClick } = this.props;
    let titleContent = null;
    let status = ciStatusMap[item.data.status];
    const metadata = get(item.data, 'result.metadata', []);
    const approval_status = get(findLast(metadata, { name: 'approval_status' }), 'value');
    let approvalResult = null as any;
    if (approval_status === approvalStatusMap.WaitApprove.value) {
      approvalResult = {
        text: i18n.t('Pending'),
        color: 'orange',
      };
    } else if (approval_status === approvalStatusMap.Reject.value) {
      const approval_reason = get(findLast(metadata, { name: 'approval_reason' }), 'value');
      approvalResult = {
        text: <Tooltip title={approval_reason}>{i18n.t('approval failed')}</Tooltip>,
        color: 'red',
      };
    } else if (approval_status === 'Canceled') {
      // 后端单独为取消审批列表中部署操作所加
      status = ciStatusMap.StopByUser;
    }

    const statusContent = (
      <span className="flex-1">
        <span
          className="yaml-editor-item-status"
          style={{ background: approvalResult ? approvalResult.color : item.data.itemStatus.toLowerCase() }}
        />
        <span className="inline-flex justify-between items-center">
          {approvalResult ? approvalResult.text : status ? status.text : '-'}
        </span>
      </span>
    );
    if (item.data.name || item.data.displayName) {
      const titleText = item.data.displayName ? `${item.data.displayName}: ${item.data.name}` : item.data.name;
      titleContent = (
        <div className="yaml-editor-pipeline-item-title nowrap">
          <Tooltip title={titleText}>{titleText}</Tooltip>
        </div>
      );
    }

    const mergedClassNames = classnames(
      'yaml-editor-pipeline-item',
      className,
      item.data.status === 'Disabled' ? 'disabled-item' : '',
    );

    const timeContent =
      time >= 0 ? (
        <span>
          <CustomIcon type="shijian" />
          <span>{secondsToTime(time || item.data.costTimeSec)}</span>
        </span>
      ) : null;

    const logoUrl = get(item.data, 'logoUrl');
    const icon = logoUrl ? (
      <img src={logoUrl} alt="logo" className="pipeline-item-icon" />
    ) : (
      <CustomIcon className="pipeline-item-icon" type="wfw" color />
    );

    const Container = this.isEmptyExtraInfo() ? Popover : React.Fragment;
    return (
      <Container {...this.renderTooltipTitle()}>
        <div onClick={() => onClick && onClick(item.data, 'node')} className={mergedClassNames}>
          {icon}
          <span className="yaml-editor-item-title-name">
            <div className="flex justify-between items-center">
              {titleContent}
              <span className="pipeline-node-icon">{this.renderIcon()}</span>
            </div>
            <div className="flex justify-between items-center">
              {statusContent}
              {timeContent}
            </div>
          </span>
          {this.renderPoints()}
        </div>
      </Container>
    );
  }
Example #6
Source File: domain-modal.tsx    From erda-ui with GNU Affero General Public License v3.0 4 votes vote down vote up
DomainModal = (props: IProps) => {
  const [form] = Form.useForm();
  const { visible, serviceName, onCancel } = props;
  const {
    id: runtimeId,
    releaseId,
    clusterType,
    extra: { workspace },
  } = runtimeStore.useStore((s: any) => s.runtimeDetail);
  const domainMap = runtimeDomainStore.useStore((s) => s.domainMap);
  const { projectId } = routeInfoStore.useStore((s) => s.params);

  const initDomains = cloneDeep(domainMap[serviceName]);
  const [{ domains }, updater] = useUpdate({
    domains: map(initDomains, (x) => ({ ...x, id: uniqueId() })),
  });

  React.useEffect(() => {
    if (visible) {
      updater.domains(cloneDeep(map(domainMap[serviceName], (x) => ({ ...x, id: uniqueId() }))) as IDomain[]);
    }
  }, [domainMap, serviceName, updater, visible]);

  const saveConfig = () => {
    const doneSaveConfig = () => {
      domainMap[serviceName] = domains;
      setLS(`${runtimeId}_domain`, domainMap);
      onCancel();
    };
    form.validateFields().then((values: any) => {
      map(values, (realValue, keyStr) => {
        const [domainType, name, id] = keyStr.split('@');
        const target = id ? find(domains, (x) => x.id === id) : findLast(domains, domainType);
        name && (target[name] = realValue);
      });
      if (!isEqual(domainMap[serviceName], domains)) {
        if (['k8s', 'edas'].includes(clusterType)) {
          runtimeDomainStore
            .updateK8SDomain({
              runtimeId,
              releaseId,
              serviceName,
              domains: map(
                filter(
                  domains,
                  (domain) =>
                    domain.domainType !== 'PACKAGE' &&
                    ((domain.domainType === 'DEFAULT' && domain.customDomain) || domain.domainType !== 'DEFAULT'),
                ),
                (domain) => (domain.domainType === 'DEFAULT' ? domain.customDomain + domain.rootDomain : domain.domain),
              ),
            })
            .then(() => {
              setTimeout(() => {
                // TODO: refactor
                location.reload();
              }, 1000);
            });
        } else {
          doneSaveConfig();
          runtimeStore.setHasChange(true);
        }
      } else {
        message.warning(i18n.t('dop:no change'));
      }
    });
  };

  const addCustom = () => {
    if (domains.length >= 1) {
      updater.domains([
        ...domains,
        {
          domainType: 'CUSTOM',
          packageId: '',
          tenantGroup: '',
          appName: '',
          domain: '',
          customDomain: '',
          rootDomain: '',
          useHttps: true,
          id: uniqueId(),
        },
      ]);
    }
  };

  const deleteCustom = (index: number) => {
    const newList = [...domains];
    newList.splice(index, 1);
    updater.domains(newList);
  };

  const hrefparams = React.useMemo(() => {
    let tenantGroup = '';
    let packageId = '';
    if (Array.isArray(domains)) {
      packageId = domains[0]?.packageId;
      tenantGroup = domains[0]?.tenantGroup;
    }
    return {
      tenantGroup,
      packageId,
    };
  }, [domains]);

  const gotoGetwayDetail = () => {
    const { tenantGroup, packageId } = hrefparams;
    // /microService/{projectId}/{env}/{tenantGroup}/gateway/api-package/{packageId}/detail'
    // const href = `/microService/${projectId}/${workspace}/${tenantGroup}/gateway/api-package/${packageId}/detail`;
    goTo(goTo.pages.getwayDetail, {
      projectId,
      env: workspace,
      packageId,
      tenantGroup,
    });
  };

  const packageDomain = domains.filter((item) => item.domainType === 'PACKAGE');

  return (
    <Modal
      title={
        <span>
          {serviceName} {i18n.t('runtime:Domain settings').toLowerCase()}
        </span>
      }
      visible={visible}
      destroyOnClose
      onOk={saveConfig}
      onCancel={onCancel}
    >
      <Form layout="vertical" form={form}>
        <div className="config-item ml-3">
          <div className="flex justify-between items-center config-item-title font-medium text-base mb-2">
            <span style={{ marginRight: '40px' }}>
              {hrefparams.packageId && hrefparams.tenantGroup ? (
                <span className="text-xs fake-link" onClick={gotoGetwayDetail}>
                  {i18n.t('runtime:route rule configuration')}
                </span>
              ) : null}
            </span>
          </div>
          {map(domains, ({ domainType, customDomain, rootDomain, domain, id }, index) => {
            return domainType === 'DEFAULT' ? (
              <div key={id} className="default-area">
                <Row>
                  <Col span={22}>
                    <FormItem
                      label={firstCharToUpper(i18n.t('domain'))}
                      name={`${domainType}@customDomain@${id}`}
                      initialValue={customDomain}
                      rules={[
                        // { required: true, message: i18n.t('runtime:please fill in the domain name') },
                        {
                          // 公司内项目不允许包含. 不允许有4级域名
                          pattern: rootDomain.includes('terminus')
                            ? /^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}$/
                            : /^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})*$/,
                          message: i18n.t('runtime:please fill in the correct domain name'),
                        },
                      ]}
                    >
                      <Input
                        placeholder={i18n.t('runtime:please fill in the domain name')}
                        addonAfter={rootDomain}
                        autoComplete="off"
                      />
                    </FormItem>
                  </Col>
                </Row>
                <div className="custom-domain" key="custom">
                  <span className="text-default">{i18n.t('runtime:Custom domain')}</span>
                </div>
              </div>
            ) : domainType === 'CUSTOM' ? (
              <Row key={id} align="middle">
                <Col span={22}>
                  <FormItem className="hidden" name={`${domainType}@@${id}`} initialValue={serviceName}>
                    <Input />
                  </FormItem>
                  <FormItem
                    name={`${domainType}@domain@${id}`}
                    initialValue={domain}
                    rules={[
                      { required: true, message: i18n.t('runtime:please fill in the custom domain name') },
                      {
                        pattern: /^[a-zA-Z0-9*][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9*][-a-zA-Z0-9]{0,62})+\.?$/,
                        message: i18n.t('runtime:please fill in the correct domain name'),
                      },
                    ]}
                  >
                    <InputItem onDelete={() => deleteCustom(index)} />
                  </FormItem>
                </Col>
              </Row>
            ) : null;
          })}

          <div className="add-domain-icon">
            <ErdaIcon
              type="add-one"
              className="hover-active cursor-pointer mt-1 text-black-4"
              onClick={() => addCustom()}
              size="18"
            />
          </div>
          {packageDomain?.length ? (
            <div>
              <div className="mb-2 text-default">{i18n.t('msp:Endpoint')}</div>
              {packageDomain.map((item) => (
                <div key={item.domain} className="mb-1">
                  {item.domain}
                </div>
              ))}
            </div>
          ) : null}
        </div>
      </Form>
    </Modal>
  );
}