rxjs/operators#reduce TypeScript Examples

The following examples show how to use rxjs/operators#reduce. 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: report.service.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
getAllTeamExtendedReports(
    config: Partial<{ order: string; queryParams: any }> = {
      order: '',
      queryParams: {},
    }
  ) {
    return this.getTeamReportsCount().pipe(
      switchMap((count) => {
        count = count > 50 ? count / 50 : 1;
        return range(0, count);
      }),
      concatMap((page) =>
        this.getTeamReports({ offset: 50 * page, limit: 50, ...config.queryParams, order: config.order })
      ),
      map((res) => res.data),
      reduce((acc, curr) => acc.concat(curr), [] as ExtendedReport[])
    );
  }
Example #2
Source File: index.ts    From dbm with Apache License 2.0 6 votes vote down vote up
manifest$ = merge(
  ...Object.entries({
    "**/*.scss": stylesheets$,
    "**/*.ts*":  javascripts$
  })
    .map(([pattern, observable$]) => (
      defer(() => process.argv.includes("--watch")
        ? watch(pattern, { cwd: "src" })
        : EMPTY
      )
        .pipe(
          startWith("*"),
          switchMapTo(observable$.pipe(toArray()))
        )
    ))
)
  .pipe(
    scan((prev, mapping) => (
      mapping.reduce((next, [key, value]) => (
        next.set(key, value.replace(`${base}/`, ""))
      ), prev)
    ), new Map<string, string>()),
  )
Example #3
Source File: report.service.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
getApproversInBulk(rptIds) {
    if (!rptIds || rptIds.length === 0) {
      return of([]);
    }
    const count = rptIds.length > 50 ? rptIds.length / 50 : 1;
    return range(0, count).pipe(
      map((page) => rptIds.slice(page * 50, (page + 1) * 50)),
      concatMap((rptIds) => this.apiService.get('/reports/approvers', { params: { report_ids: rptIds } })),
      reduce((acc, curr) => acc.concat(curr), [])
    );
  }
Example #4
Source File: index.ts    From dbm with Apache License 2.0 6 votes vote down vote up
emojis$ = defer(() => resolve("venv/**/twemoji_db.py"))
  .pipe(
    switchMap(file => read(file)),
    map(data => {
      const [, payload] = data.match(/^emoji = ({.*})$.alias/ms)!
      return Object.entries<TwemojiIcon>(JSON.parse(payload))
        .reduce((index, [name, { unicode }]) => index.set(
          name.replace(/(^:|:$)/g, ""),
          `${unicode}.svg`
        ), new Map<string, string>())
    })
  )
Example #5
Source File: corporate-credit-card-expense.service.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
getAllv2CardTransactions(config: Partial<{ order: string; queryParams: any }>): Observable<CorporateCardExpense[]> {
    return this.getv2CardTransactionsCount(config.queryParams).pipe(
      switchMap((count) => {
        count = count > 50 ? count / 50 : 1;
        return range(0, count);
      }),
      concatMap((page) =>
        this.getv2CardTransactions({
          offset: 50 * page,
          limit: 50,
          queryParams: config.queryParams,
          order: config.order,
        })
      ),
      map((res) => res.data),
      reduce((acc, curr) => acc.concat(curr))
    );
  }
Example #6
Source File: service.effects.ts    From digital-bank-ui with Mozilla Public License 2.0 5 votes vote down vote up
private fetchPermissions(tenantId: string, username: string, accessToken: string): Observable<FimsPermission[]> {
    return this.authenticationService.getUserPermissions(tenantId, username, accessToken).pipe(
      mergeMap((permissions: Permission[]) => observableFrom(permissions)),
      map((permission: Permission) => this.mapPermissions(permission)),
      reduce((acc: FimsPermission[], permissions: FimsPermission[]) => acc.concat(permissions), []),
    );
  }
Example #7
Source File: capture-receipt.component.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
addMultipleExpensesToQueue(base64ImagesWithSource: Image[]) {
    return from(base64ImagesWithSource).pipe(
      concatMap((res: Image) => this.addExpenseToQueue(res)),
      reduce((acc, curr) => acc.concat(curr), [])
    );
  }
Example #8
Source File: index.ts    From dbm with Apache License 2.0 5 votes vote down vote up
icons$ = defer(() => resolve("**/*.svg", { cwd: "material/.icons" }))
  .pipe(
    reduce((index, file) => index.set(
      file.replace(/\.svg$/, "").replace(/\//g, "-"),
      file
    ), new Map<string, string>())
  )
Example #9
Source File: view-expense.page.ts    From fyle-mobile-app with MIT License 4 votes vote down vote up
ionViewWillEnter() {
    this.setupNetworkWatcher();
    const txId = this.activatedRoute.snapshot.params.id;

    this.etxnWithoutCustomProperties$ = this.updateFlag$.pipe(
      switchMap(() => this.transactionService.getEtxn(txId)),
      shareReplay(1)
    );

    this.etxnWithoutCustomProperties$.subscribe((res) => {
      this.reportId = res.tx_report_id;
    });

    this.customProperties$ = this.etxnWithoutCustomProperties$.pipe(
      concatMap((etxn) =>
        this.customInputsService.fillCustomProperties(etxn.tx_org_category_id, etxn.tx_custom_properties, true)
      ),
      shareReplay(1)
    );

    this.etxn$ = combineLatest([this.etxnWithoutCustomProperties$, this.customProperties$]).pipe(
      map((res) => {
        res[0].tx_custom_properties = res[1];
        return res[0];
      }),
      finalize(() => this.loaderService.hideLoader()),
      shareReplay(1)
    );

    this.etxn$.subscribe((etxn) => {
      this.isExpenseFlagged = etxn.tx_manual_flag;

      if (etxn.tx_amount && etxn.tx_orig_amount) {
        this.exchangeRate = etxn.tx_amount / etxn.tx_orig_amount;
      }

      if (etxn.source_account_type === 'PERSONAL_ADVANCE_ACCOUNT') {
        this.paymentMode = 'Advance';
        this.paymentModeIcon = 'fy-non-reimbursable';
      } else if (etxn.source_account_type === 'PERSONAL_CORPORATE_CREDIT_CARD_ACCOUNT') {
        this.paymentMode = 'Corporate Card';
        this.paymentModeIcon = 'fy-unmatched';
        this.isCCCTransaction = true;
      } else if (etxn.tx_skip_reimbursement) {
        this.paymentMode = 'Paid by Company';
        this.paymentModeIcon = 'fy-non-reimbursable';
      } else {
        this.paymentMode = 'Paid by Employee';
        this.paymentModeIcon = 'fy-reimbursable';
      }

      if (this.isCCCTransaction) {
        this.matchingCCCTransaction$ = this.corporateCreditCardExpenseService
          .getEccceByGroupId(etxn.tx_corporate_credit_card_expense_group_id)
          .pipe(
            map(
              (matchedExpense) => matchedExpense[0] && (this.paymentModeIcon = 'fy-matched') && matchedExpense[0].ccce
            )
          );
        this.matchingCCCTransaction$.subscribe((cardTxn) => {
          this.cardNumber = cardTxn?.card_or_account_number;
        });
      }
      this.foreignCurrencySymbol = getCurrencySymbol(etxn.tx_orig_currency, 'wide');
      this.etxnCurrencySymbol = getCurrencySymbol(etxn.tx_currency, 'wide');
    });

    forkJoin([this.offlineService.getExpenseFieldsMap(), this.etxn$.pipe(take(1))])
      .pipe(
        map(([expenseFieldsMap, etxn]) => {
          this.projectFieldName = expenseFieldsMap?.project_id[0]?.field_name;
          const isProjectMandatory = expenseFieldsMap?.project_id && expenseFieldsMap?.project_id[0]?.is_mandatory;
          this.isProjectShown = this.orgSettings?.projects?.enabled && (etxn.tx_project_name || isProjectMandatory);
        })
      )
      .subscribe(noop);

    this.policyViloations$ = this.etxnWithoutCustomProperties$.pipe(
      concatMap((etxn) => this.statusService.find('transactions', etxn.tx_id)),
      map((comments) => comments.filter(this.isPolicyComment))
    );

    this.comments$ = this.statusService.find('transactions', txId);
    this.view = this.activatedRoute.snapshot.params.view;

    this.canFlagOrUnflag$ = this.etxnWithoutCustomProperties$.pipe(
      filter(() => this.view === ExpenseView.team),
      map(
        (etxn) =>
          ['COMPLETE', 'POLICY_APPROVED', 'APPROVER_PENDING', 'APPROVED', 'PAYMENT_PENDING'].indexOf(etxn.tx_state) > -1
      )
    );

    this.canDelete$ = this.etxnWithoutCustomProperties$.pipe(
      filter(() => this.view === ExpenseView.team),
      switchMap((etxn) =>
        this.reportService.getTeamReport(etxn.tx_report_id).pipe(map((report) => ({ report, etxn })))
      ),
      map(({ report, etxn }) => {
        if (report.rp_num_transactions === 1) {
          return false;
        }
        return ['PAYMENT_PENDING', 'PAYMENT_PROCESSING', 'PAID'].indexOf(etxn.tx_state) < 0;
      })
    );

    this.isAmountCapped$ = this.etxn$.pipe(
      map((etxn) => this.isNumber(etxn.tx_admin_amount) || this.isNumber(etxn.tx_policy_amount))
    );

    this.offlineService.getOrgSettings().subscribe((orgSettings) => {
      this.orgSettings = orgSettings;
      this.isUnifyCcceExpensesSettingsEnabled =
        this.orgSettings?.unify_ccce_expenses_settings?.allowed &&
        this.orgSettings?.unify_ccce_expenses_settings?.enabled;
    });

    this.offlineService
      .getExpenseFieldsMap()
      .pipe(
        map((expenseFieldsMap) => {
          this.merchantFieldName = expenseFieldsMap.vendor_id[0]?.field_name;
        })
      )
      .subscribe(noop);

    this.isCriticalPolicyViolated$ = this.etxn$.pipe(
      map((etxn) => this.isNumber(etxn.tx_policy_amount) && etxn.tx_policy_amount < 0.0001)
    );

    this.getPolicyDetails(txId);

    const editExpenseAttachments = this.etxn$.pipe(
      take(1),
      switchMap((etxn) => this.fileService.findByTransactionId(etxn.tx_id)),
      switchMap((fileObjs) => from(fileObjs)),
      concatMap((fileObj: any) =>
        this.fileService.downloadUrl(fileObj.id).pipe(
          map((downloadUrl) => {
            fileObj.url = downloadUrl;
            const details = this.getReceiptDetails(fileObj);
            fileObj.type = details.type;
            fileObj.thumbnail = details.thumbnail;
            return fileObj;
          })
        )
      ),
      reduce((acc, curr) => acc.concat(curr), [])
    );

    this.attachments$ = editExpenseAttachments;
    this.updateFlag$.next();
    this.attachments$.subscribe(noop, noop, () => {
      this.isLoading = false;
    });

    const etxnIds =
      this.activatedRoute.snapshot.params.txnIds && JSON.parse(this.activatedRoute.snapshot.params.txnIds);
    this.numEtxnsInReport = etxnIds.length;
    this.activeEtxnIndex = parseInt(this.activatedRoute.snapshot.params.activeIndex, 10);
  }