Skip to content

feat: add pChain #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .github/workflows/deploy-docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ name: Vercel Deployment Development
env:
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}

on:
push:
branches:
- main
tags:
- 'v*'

# This is what will cancel the workflow
concurrency:
Expand Down
5 changes: 4 additions & 1 deletion docs/.vitepress/locale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,10 @@ export function getLocaleConfig(lang: string) {
},
{
text: t('Promise Utilities'),
items: [{ text: 'delay', link: '/reference/promise/delay' }],
items: [
{ text: 'delay', link: '/reference/promise/delay' },
{ text: 'pChain', link: '/reference/promise/pChain' },
],
},
{
text: t('String Utilities'),
Expand Down
2 changes: 1 addition & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"@nolebase/vitepress-plugin-highlight-targeted-heading": "^2.2.1",
"@shikijs/vitepress-twoslash": "^1.10.3",
"@vitejs/plugin-vue-jsx": "^4.0.0",
"js-utils-es": "^1.0.5",
"js-utils-es": "^1.0.6",
"unocss": "^0.61.3",
"vite": "^5.3.3",
"vitepress": "^1.3.0",
Expand Down
51 changes: 51 additions & 0 deletions docs/reference/promise/pChain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# pChain

Utility for managing multiple promises.

## Signature

```typescript
function pChain<T = any>(items?: Iterable<T>): PInstance<T>;
```

### Parameters

- `items` (`Iterable`): An optional iterable of items to chain.

### Returns

(`PInstance<void>`): A `PInstance` object that can be used to chain promises.

## Description

```ts
declare class PInstance<T = any> extends Promise<Awaited<T>[]> {
items: Iterable<T>;
private promises;
get promise(): Promise<Awaited<T>[]>;
constructor(items?: Iterable<T>);
add(...args: (T | Promise<T>)[]): void;
map<U>(fn: (value: Awaited<T>, index: number) => U): PInstance<Promise<U>>;
filter(fn: (value: Awaited<T>, index: number) => boolean | Promise<boolean>): PInstance<Promise<T>>;
forEach(fn: (value: Awaited<T>, index: number) => void): Promise<void>;
reduce<U>(fn: (previousValue: U, currentValue: Awaited<T>, currentIndex: number, array: Awaited<T>[]) => U, initialValue: U): Promise<U>;
clear(): void;
then(fn?: () => PromiseLike<any>): Promise<any>;
catch(fn?: (err: unknown) => PromiseLike<any>): Promise<any>;
finally(fn?: () => void): Promise<Awaited<T>[]>;
}
```

## Examples

```typescript
import { pChain } from 'js-utils-es/promise';

const items = [1, 2, 3, 4, 5];

await pChain(items)
.map(async i => await multiply(i, 3))
.filter(async i => await isEven(i))

// Result: [6, 12]
```
19 changes: 19 additions & 0 deletions src/promise/pChain.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { describe, expect, it } from 'vitest'
import { pChain } from './pChain'

const timeout = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

describe('pChain', () => {
it('chain array map', async () => {
expect(
await pChain([1, 2, 3, 4, 5])
.map(async (i) => {
await timeout(10)
return i * i
})
.filter(i => i > 10)
.reduce((a, b) => a + b, 0),
)
.toEqual(41)
})
})
96 changes: 96 additions & 0 deletions src/promise/pChain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/**
* Internal marker for filtered items
*/
const VOID = Symbol('p-void')

class PInstance<T = any> extends Promise<Awaited<T>[]> {
private promises = new Set<T | Promise<T>>()

get promise(): Promise<Awaited<T>[]> {
const items = [...Array.from(this.items), ...Array.from(this.promises)]

const batch = Promise.all(items)

return batch.then(l => l.filter((i: any) => i !== VOID))
}

constructor(public items: Iterable<T> = []) {
super(() => {})
}

add(...args: (T | Promise<T>)[]) {
args.forEach((i) => {
this.promises.add(i)
})
}

map<U>(fn: (value: Awaited<T>, index: number) => U): PInstance<Promise<U>> {
return new PInstance(
Array.from(this.items)
.map(async (i, idx) => {
const v = await i
if ((v as any) === VOID)
return VOID as unknown as U
return fn(v, idx)
}),
)
}

filter(fn: (value: Awaited<T>, index: number) => boolean | Promise<boolean>): PInstance<Promise<T>> {
return new PInstance(
Array.from(this.items)
.map(async (i, idx) => {
const v = await i
const r = await fn(v, idx)
if (!r)
return VOID as unknown as T
return v
}),
)
}

forEach(fn: (value: Awaited<T>, index: number) => void): Promise<void> {
return this.map(fn).then()
}

reduce<U>(fn: (previousValue: U, currentValue: Awaited<T>, currentIndex: number, array: Awaited<T>[]) => U, initialValue: U): Promise<U> {
return this.promise.then(array => array.reduce(fn, initialValue))
}

clear() {
this.promises.clear()
}

then(fn?: () => PromiseLike<any>) {
const p = this.promise
if (fn)
return p.then(fn)
else
return p
}

catch(fn?: (err: unknown) => PromiseLike<any>) {
return this.promise.catch(fn)
}

finally(fn?: () => void) {
return this.promise.finally(fn)
}
}

/**
* Utility for managing multiple promises.
*
* @example
* ```js
* const items = [1, 2, 3, 4, 5]
*
* await p(items)
* .map(async i => await multiply(i, 3))
* .filter(async i => await isEven(i))
* // [6, 12]
* ```
*/
export function pChain<T = any>(items?: Iterable<T>): PInstance<T> {
return new PInstance(items)
}
Loading