Skip to content

Commit

Permalink
initial implementation of retrySync
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaly-t committed Aug 2, 2024
1 parent cfb50d7 commit d87e87a
Showing 1 changed file with 40 additions and 14 deletions.
54 changes: 40 additions & 14 deletions src/ops/async/retry.ts → src/ops/retry.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {$A, IterationState, Operation} from '../../types';
import {isPromiseLike} from '../../typeguards';
import {createOperation, throwOnSync} from '../../utils';
import {$A, IterationState, Operation} from '../types';
import {isPromiseLike} from '../typeguards';
import {createOperation} from '../utils';

/**
* When an asynchronous iterable rejects, it retries getting the value specified number of times.
Expand Down Expand Up @@ -64,19 +64,45 @@ export function retry<T>(
): Operation<T, T>;

export function retry(...args: unknown[]) {
return createOperation(throwOnSync('retry'), retryAsync, args);
return createOperation(retrySync, retryAsync, args);
}

function retryAsync<T>(
iterable: AsyncIterable<T>,
retry:
| number
| ((
index: number,
attempts: number,
state: IterationState
) => boolean | Promise<boolean>)
): AsyncIterable<T> {
type Retry<T> = number | ((index: number, attempts: number, state: IterationState) => T);

Check failure on line 70 in src/ops/retry.ts

View workflow job for this annotation

GitHub Actions / Linting Checks

Replace `·number` with `⏎····|·number⏎···`

function retrySync<T>(iterable: Iterable<T>, retry: Retry<boolean>): Iterable<T> {

Check failure on line 72 in src/ops/retry.ts

View workflow job for this annotation

GitHub Actions / Linting Checks

Replace `iterable:·Iterable<T>,·retry:·Retry<boolean>` with `⏎····iterable:·Iterable<T>,⏎····retry:·Retry<boolean>⏎`
return {
[Symbol.iterator](): Iterator<T> {
const i = iterable[Symbol.iterator]();
const state: IterationState = {};
let index = 0;
const cb = typeof retry === 'function' && retry;
let attempts = 0;
const retriesNumber = !cb && retry > 0 ? retry : 0;
let leftTries = retriesNumber;
return {
next(): IteratorResult<T> {
do {
try {
const a = i.next();
index++;
attempts = 0;
leftTries = retriesNumber;
return a;
} catch (err) {
const r = cb && cb(index, attempts++, state);
if (r || leftTries--) {
continue;
}
throw err; // out of attempts, re-throw
}
} while (true);
}
};
}
};
}

function retryAsync<T>(iterable: AsyncIterable<T>, retry: Retry<boolean | Promise<boolean>>): AsyncIterable<T> {

Check failure on line 105 in src/ops/retry.ts

View workflow job for this annotation

GitHub Actions / Linting Checks

Replace `iterable:·AsyncIterable<T>,·retry:·Retry<boolean·|·Promise<boolean>>` with `⏎····iterable:·AsyncIterable<T>,⏎····retry:·Retry<boolean·|·Promise<boolean>>⏎`
return {
[$A](): AsyncIterator<T> {
const i = iterable[$A]();
Expand Down

0 comments on commit d87e87a

Please sign in to comment.