### Install Project Dependencies
Source: https://github.com/marpple/fxts/blob/main/website/README.md
Run this command in the project root to install all necessary npm packages.
```bash
npm install
```
--------------------------------
### Install FxTS with Yarn
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/getting-started.md
Use this command to install the FxTS core package using Yarn.
```shell
yarn add @fxts/core
```
--------------------------------
### Install FxTS Core Package
Source: https://github.com/marpple/fxts/blob/main/README.md
Install the FxTS core package using npm. This is the initial step to use the library's functionalities.
```bash
npm install @fxts/core
```
--------------------------------
### Start Local Development Server
Source: https://github.com/marpple/fxts/blob/main/website/README.md
Use this command to launch the VitePress development server for live previewing changes.
```bash
npm run dev
```
--------------------------------
### Stub Frontmatter Example
Source: https://github.com/marpple/fxts/blob/main/website/i18n/README.md
Example of frontmatter embedded in a stub file. It includes the file ID, a 'translated: false' marker, and the SHA-256 content hash of the English source.
```yaml
---
id: throttle
translated: false
sourceHash: "3dee719216b52c51"
---
```
--------------------------------
### Asynchronous Lazy Movie Recommendation
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/lazy-evaluation.md
An advanced example demonstrating asynchronous lazy evaluation for fetching and filtering movie data. It uses `range(year, Infinity)` and `toAsync` to handle potentially infinite streams of data, applying lazy operations until a result is found or the stream is exhausted.
```typescript
const fetchMovie = async (year: number) =>
fetch(`https://api.movie.xxx/${year}`);
const recommendMovie = async (year: number, rating: number) =>
pipe(
range(year, Infinity),
toAsync,
map(fetchMovie),
map((res) => res.json()),
filter((movie) => movie.rating >= rating),
head,
);
await recommendMovie(2020, 9);
```
--------------------------------
### Eager Array Evaluation Example
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/lazy-evaluation.md
This demonstrates standard JavaScript array method chaining where each operation creates a new array and traverses all elements, which can be inefficient for large datasets.
```typescript
const sum = (a: number, b: number) => a + b;
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.filter((a) => a % 2 === 0)
.map((a) => a * a)
.reduce(sum);
```
--------------------------------
### Concurrent Request Handling with FxTS
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/handle-concurrency.md
Handles concurrent asynchronous requests for an infinite dataset, controlling the load size. This example demonstrates how `concurrent` reduces execution time compared to sequential processing.
```typescript
// prettier-ignore
import { pipe, toAsync, range, map, filter, take, each, concurrent } from "@fxts/core";
const fetchApi = (page) =>
new Promise((resolve) => setTimeout(() => resolve(page), 1000));
await pipe(
range(Infinity),
toAsync,
map(fetchApi), // 0,1,2,3,4,5
filter((a) => a % 2 === 0),
take(3), // 0,2,4
concurrent(3), // If this line does not exist, it will take a total of 6 seconds.
each(console.log), // 2 seconds
);
```
--------------------------------
### Concurrent Operation with AsyncIterable
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/method-chaining.md
Demonstrates handling concurrent operations on an `AsyncIterable` using `concurrent(2)`. This example uses `delay` and `range` to simulate asynchronous work.
```typescript
/**
*
* evaluation
* ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐
* │ 1 │──│ 2 │──│ 3 │──│ 4 │──│ 5 │──│ 6 │
* └──┬──┘ └──┬──┘ └──┬──┘ └──┬──┘ └──┬──┘ └──┬──┘
* map │ │ │ │ │ │
* concurrent(2) (1) (1) (2) (2) (3) (3)
* │ │ │ │ │ │
* ▼ ▼ ▼ ▼ ▼ ▼
*/
await fx(toAsync(range(1, 7)))
// async function returns
.map(async (a) => delay(100, a))
.concurrent(2)
.consume(); // It takes approximately 300ms.
```
--------------------------------
### Async Operations with Concurrency
Source: https://github.com/marpple/fxts/blob/main/website/docs/public/llms.txt
Handle asynchronous operations in parallel using concurrent(). This example fetches data concurrently and limits the number of parallel operations.
```typescript
import { pipe, toAsync, map, concurrent, toArray } from "@fxts/core";
await pipe(
[1, 2, 3, 4],
toAsync,
map(async a => await fetchData(a)),
concurrent(2), // Process 2 items in parallel
toArray
);
```
--------------------------------
### Pipe Style Data Transformation
Source: https://github.com/marpple/fxts/blob/main/website/docs/public/llms.txt
Use pipe() to compose functions for readable data transformations. This example chains map, filter, and take operations.
```typescript
import { pipe, map, filter, take, toArray } from "@fxts/core";
pipe(
[1, 2, 3, 4, 5],
map(a => a * 2),
filter(a => a > 4),
take(2),
toArray
); // [6, 8]
```
--------------------------------
### Concurrent Async Operations with concurrent
Source: https://github.com/marpple/fxts/blob/main/README.md
Handles multiple asynchronous operations in parallel using the `concurrent` function. This example fetches Wikipedia page content and counts words, demonstrating how concurrency affects execution time.
```typescript
import { concurrent, countBy, flat, fx, map, pipe, toAsync } from "@fxts/core";
// maybe 1 seconds api
const fetchWiki = (page: string) =>
fetch(`https://en.wikipedia.org/w/api.php?action=parse&page=${page}`);
const countWords = async (concurrency: number) =>
pipe(
["html", "css", "javascript", "typescript"],
toAsync,
map(fetchWiki),
map((res) => res.text()),
map((words) => words.split(" ")),
flat,
concurrent(concurrency),
countBy((word) => word),
);
await countWords(); // 4 seconds
await countWords(2); // 2 seconds
```
--------------------------------
### Lazy Evaluation with FxTS Pipe
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/lazy-evaluation.md
Demonstrates FxTS lazy evaluation where operations are composed as functions and only evaluated as needed. This example shows how `take(2)` limits evaluation, and `filter` also processes lazily.
```typescript
pipe(
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
filter((a) => a % 2 === 0), // [0, 2]
map((a) => a * a), // [0, 4]
take(2), // [0, 4]
reduce(sum),
);
```
--------------------------------
### Lazy Evaluation Pipeline Example
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/how-to-debug.md
Demonstrates a lazy evaluation pipeline to find the 13th of Fridays. Note that functions return `IterableIterator`, and evaluation only occurs when `toArray` is called.
```typescript
const addDate = (from: Date, n: number) => {
const clone = new Date(from);
clone.setDate(n);
return clone;
};
const addDateFrom = (from: Date) => (n: number) => addDate(from, n);
const is13thOfFriday = (date: Date) =>
date.getDate() === 13 && date.getDay() === 5;
const formatYYYYMMDD = (date: Date) => {
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
};
pipe(
range(1, Infinity),
map(addDateFrom(new Date(2000, 0, 1))),
filter(is13thOfFriday),
map(formatYYYYMMDD),
take(5),
toArray,
console.log
);
// ['2000-10-13', '2001-4-13', '2001-7-13', '2002-9-13', '2002-12-13']
```
--------------------------------
### Build Project for Production
Source: https://github.com/marpple/fxts/blob/main/website/README.md
Execute this command to create a production-ready build of the website.
```bash
npm run build
```
--------------------------------
### Generate API Documentation
Source: https://github.com/marpple/fxts/blob/main/website/README.md
Navigate to the generate-api-docs directory and run 'make' to generate API documentation. Ensure FxTS is built first.
```bash
cd generate-api-docs
make
```
--------------------------------
### Run All Tests
Source: https://github.com/marpple/fxts/blob/main/CONTRIBUTING.md
Execute the entire test suite for the project.
```bash
npm test
```
--------------------------------
### Run All Checks Before Submitting
Source: https://github.com/marpple/fxts/blob/main/CONTRIBUTING.md
Execute linting, formatting, type checking, and the test suite to ensure code quality and correctness.
```bash
npm run lint
npm run prettier
npm run compile:check
npm test
```
--------------------------------
### Basic Usage with pipe and fx
Source: https://github.com/marpple/fxts/blob/main/README.md
Demonstrates function composition using `pipe` or method chaining with `fx`. Both achieve the same result of processing a range of numbers with map, filter, take, and each operations.
```typescript
import { each, filter, fx, map, pipe, range, take } from "@fxts/core";
pipe(
range(10),
map((a) => a + 10),
filter((a) => a % 2 === 0),
take(2),
each((a) => console.log(a)),
);
// chaining
fx(range(10))
.map((a) => a + 10)
.filter((a) => a % 2 === 0)
.take(2)
.each((a) => console.log(a));
```
--------------------------------
### Clone FxTS Repository
Source: https://github.com/marpple/fxts/blob/main/CONTRIBUTING.md
Clone your forked repository to your local machine and navigate into the project directory.
```bash
git clone https://github.com/YOUR_USERNAME/FxTS.git
cd FxTS
```
--------------------------------
### Define Supported Locales and Doc Directories
Source: https://github.com/marpple/fxts/blob/main/website/i18n/README.md
Configure supported locales and document directories. Add new locales to the LOCALES array to automatically generate stubs for existing documentation.
```typescript
export const LOCALES = ["ja", "ko", "zh"] as const; // Supported locales
export const DOC_DIRS = ["api", "guide"] as const; // Doc directories to track
```
--------------------------------
### Basic Method Chaining with fx
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/method-chaining.md
Demonstrates chaining `filter`, `map`, `take`, and `reduce` operations on an array. Also shows chaining `map`, `take`, and `toArray` on a string.
```typescript
fx([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.filter((a) => a % 2 === 0) // [0, 2]
.map((a) => a * a) // [0, 4]
.take(2) // [0, 4]
.reduce(sum); // 4
```
```typescript
fx("abc")
.map((a) => a.toUpperCase()) // ["A", "B"]
.take(2)
.toArray(); // ["A", "B"]
```
--------------------------------
### Push Changes to Fork
Source: https://github.com/marpple/fxts/blob/main/CONTRIBUTING.md
Push your local feature branch to your forked repository on origin.
```bash
git push origin feature/your-feature-name
```
--------------------------------
### Run i18n Sync and Check Scripts
Source: https://github.com/marpple/fxts/blob/main/website/i18n/README.md
Execute the i18n synchronization and validation scripts from the website/generate-api-docs/ directory. 'i18n-sync' generates stubs, removes orphans, and updates status. 'i18n-check' performs a dry-run validation, used in CI.
```bash
# From website/generate-api-docs/
make i18n-sync # Generate stubs, remove orphans, update status
make i18n-check # Dry-run validation (used in CI)
```
--------------------------------
### Eager Array Evaluation with Intermediate Steps
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/lazy-evaluation.md
Illustrates the intermediate array creation and traversal that occurs with standard JavaScript array methods, highlighting potential inefficiencies.
```typescript
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.filter((a) => a % 2 === 0) // [0, 2, 4, 6, 8]
.map((a) => a * a) // [0, 4, 16, 36, 64]
.reduce(sum); // 120
```
--------------------------------
### CDN Usage
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/getting-started.md
Include FxTS via CDN for use in HTML. This script targets es5 and includes polyfills.
```html
```
--------------------------------
### Run Tests in Watch Mode
Source: https://github.com/marpple/fxts/blob/main/CONTRIBUTING.md
Run tests continuously and automatically re-run them when file changes are detected, useful for development.
```bash
npm test -- --watch
```
--------------------------------
### Synchronous Error Handling with FxTS
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/error-handling.md
Demonstrates how to catch errors thrown by synchronous operations within an FxTS pipe. Ensure the error-throwing function is correctly placed within the pipe.
```typescript
import { map, pipe, take, toArray, toAsync } from "@fxts/core";
const syncError = (a) => {
throw new Error(`err ${a}`);
};
try {
pipe(
[1, 2, 3, 4, 5],
map(syncError),
filter((a) => a % 2 === 0),
toArray,
);
} catch (err) {
// handle err
}
```
--------------------------------
### Create Feature Branch
Source: https://github.com/marpple/fxts/blob/main/CONTRIBUTING.md
Create a new branch for your feature development, branching off from the main branch.
```bash
git checkout -b feature/your-feature-name
```
--------------------------------
### Using chain for Additional Functions
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/method-chaining.md
Illustrates how to use the `chain` method to incorporate functions not directly available as methods on the `fx` object, such as `append`.
```typescript
fx([1, 2, 3, 4])
.chain(append(5))
.map((a) => a + 10)
.toArray(); // [11, 12, 13, 14, 15]
```
--------------------------------
### Concurrent vs. Sequential Filter Execution
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/handle-concurrency.md
Illustrates the placement of `concurrent` within a pipeline. Placing `concurrent` before `filter` and `take` still allows for concurrent execution of the asynchronous `fetchApi` calls.
```typescript
await pipe(
range(Infinity),
toAsync,
map(fetchApi),
concurrent(3),
filter((a) => a % 2 === 0),
take(3),
each(console.log),
);
```
--------------------------------
### ESM Import with esm5 Submodule
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/getting-started.md
Use this import path for FxTS in JavaScript environments that do not support es2018. The esm5 submodule targets es5 and does not include polyfills.
```javascript
import { filter, map, pipe, range, reduce, take } from "@fxts/core/esm5";
```
--------------------------------
### Basic Usage in TypeScript
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/getting-started.md
Demonstrates a typical FxTS pipeline in TypeScript, processing a range of numbers with filtering, mapping, taking a subset, and reducing to a sum. Type inference for 'sum' as 'number' requires strictFunctionTypes and strictNullChecks tsc options.
```typescript
import { filter, map, pipe, range, reduce, take } from "@fxts/core";
const sum = pipe(
range(Infinity),
filter((a) => a % 5 === 0),
map((a) => a * 10),
take(10),
reduce((a, b) => a + b),
); // typeof 'sum' inferred as the number
```
--------------------------------
### Basic Function Composition with pipe
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/function-composition.md
Use `pipe` to chain functions, passing the output of one to the input of the next. This improves readability compared to nested function calls.
```typescript
import { filter, map, pipe, reduce } from "@fxts/core";
const sum = (a: number, b: number) => a + b;
const arr = [1, 2, 3, 4, 5];
pipe(
arr,
filter((a) => a % 2 === 0),
map((a) => a + 10),
reduce(sum),
);
```
--------------------------------
### Create Issues Script Behavior
Source: https://github.com/marpple/fxts/blob/main/website/i18n/README.md
Details the functionality of the 'create-issues.ts' script for GitHub Issue automation. It reads translation status, creates issues for stubbed or outdated translations, applies labels, and deduplicates by checking existing issues.
```markdown
- Reads `translation-status.json` for `stub` and `outdated` entries
- Creates one GitHub Issue per locale per file (e.g., "Translate `throttle.md` to Japanese")
- Applies labels: `translation`, `good first issue`, `lang:{locale}`
- Deduplicates by checking for existing open issues with the same title
- Auto-creates labels if they don't exist in the repository
```
--------------------------------
### Translation File States
Source: https://github.com/marpple/fxts/blob/main/website/i18n/README.md
Illustrates the lifecycle of a translation file: missing, stub, translated, and outdated. Missing files block PRs, while stub and outdated files are tracked via issues.
```markdown
missing ──► stub ──► translated
│
▼
outdated (when English source changes)
```
--------------------------------
### Utility Functions
Source: https://github.com/marpple/fxts/blob/main/website/docs/public/llms.txt
General utility functions for common programming tasks.
```APIDOC
## Utility Functions
- [debounce](https://fxts.dev/api/debounce)
- [shuffle](https://fxts.dev/api/shuffle)
```
--------------------------------
### ESM Import in JavaScript
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/getting-started.md
Standard ESM import for FxTS in JavaScript, targeting es2018 and not including polyfills.
```javascript
import { filter, map, pipe, range, reduce, take } from "@fxts/core";
```
--------------------------------
### Sync Script Operations
Source: https://github.com/marpple/fxts/blob/main/website/i18n/README.md
Outlines the sequence of operations performed by the 'sync.ts' script. It scans English files, processes locale files for missing entries and translation status, cleans up orphans, and generates a status report.
```markdown
1. Scan `docs/api/*.md` and `docs/guide/*.md` to build the English file set
2. For each locale (`ja`, `ko`, `zh`):
- **Missing files**: Create stub with English content + `translated: false` marker
- **Existing files**: Check translation status via frontmatter and content hash
3. **Orphan cleanup**: Delete locale files that have no corresponding English source
4. Write `translation-status.json` with the complete status of all files
```
--------------------------------
### Check Script Behavior
Source: https://github.com/marpple/fxts/blob/main/website/i18n/README.md
Describes the behavior of the 'check.ts' script, which is used for CI validation. It categorizes files, generates a report, and exits with a non-zero code only when missing files are detected.
```markdown
- Scans all locales and categorizes files as `missing`, `stub`, or `outdated`
- Writes `website/i18n-report.json` for CI comment generation
- Exits with code **1** only when `missing` files exist (no stub at all)
- Exits with code **0** for `stub` and `outdated` (these are tracked via Issues, not blocking)
```
--------------------------------
### CJS Import in JavaScript
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/getting-started.md
CommonJS import for FxTS in JavaScript. Individual functions can also be loaded from the Lazy submodule.
```javascript
const { filter, map, pipe, range, reduce } = require("@fxts/core");
// It can be loaded as an individual function
const take = require("@fxts/core/Lazy/take").default;
```
--------------------------------
### Asynchronous Error Handling with FxTS
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/error-handling.md
Shows how to handle errors from asynchronous operations, such as Promises rejected within an FxTS pipe. Use `await` with `pipe` for asynchronous error catching.
```typescript
import { filter, map, pipe, toArray, toAsync } from "@fxts/core";
const fetchAsyncError = (a) => Promise.reject(`err ${a}`);
try {
await pipe(
Promise.resolve([1, 2, 3, 4, 5]),
toAsync,
map(fetchAsyncError),
filter((a) => a % 2 === 0),
toArray,
);
} catch (err) {
// handle err
}
```
```typescript
import { filter, map, pipe, toArray, toAsync } from "@fxts/core";
const fetchAsyncError = (a) => Promise.reject(`err ${a}`);
try {
await pipe(
[
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3),
Promise.resolve(4),
],
toAsync,
map(fetchAsyncError),
filter((a) => a % 2 === 0),
toArray,
);
} catch (err) {
// handle err
}
```
--------------------------------
### Lazy Evaluation with Infinite Range
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/lazy-evaluation.md
Illustrates FxTS lazy evaluation with an infinite range, showcasing its ability to handle potentially infinite data structures efficiently by only computing values as required by operations like `take`.
```typescript
pipe(
range(Infinity),
filter((a) => a % 2 === 0), // [0, 2]
map((a) => a * a), // [0, 4]
take(2), // [0, 4]
reduce(sum),
);
```
--------------------------------
### Converting Iterable to AsyncIterable with toAsync
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/to-async.md
Shows how to use the `toAsync` function within a `pipe` to convert a standard `Iterable` or an `Iterable>` into an `AsyncIterable`. This enables the use of asynchronous callbacks and proper handling of promises within the iteration.
```typescript
await pipe(
numbers(), // Iterable
toAsync, // AsyncIterable
find((num) => Promise.resolve(num === 2)),
);
await pipe(
promiseNumbers(), // Iterable>
toAsync, // AsyncIterable
find((num) => Promise.resolve(num === 2)),
);
```
--------------------------------
### Handling Synchronous and Asynchronous Iterables with find
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/to-async.md
Demonstrates how the `find` function in FxTS can process both synchronous `Iterable` and asynchronous `AsyncIterable`. Note that `AsyncIterable` works with both synchronous and asynchronous callbacks, while `Iterable` does not support asynchronous callbacks or `Iterable>`.
```typescript
const numbers = function* () {
yield 1;
yield 2;
yield 3;
};
const asyncNumbers = async function* () {
yield 1;
yield 2;
yield 3;
};
find((num) => num === 2, numbers()); // 2
find((num) => num === 2, asyncNumbers()); // Promise<2>
```
--------------------------------
### Translation Status Table
Source: https://github.com/marpple/fxts/blob/main/website/i18n/README.md
Defines the meaning of each translation file state and its corresponding behavior in CI. Missing files block PRs, while stub and outdated files pass CI but are tracked.
```markdown
| State | Meaning |
| ------------ | ------------------------------------------------------ |
| `missing` | No file exists in the locale directory |
| `stub` | English content copied with `translated: false` marker |
| `translated` | Fully translated (no marker or `translated: true`) |
| `outdated` | Translated, but English source hash has changed |
```
--------------------------------
### Method Chaining with AsyncIterable
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/method-chaining.md
Shows how to chain asynchronous operations like `filter` and `map` on an `AsyncIterable`. Uses `toAsync` to create an `AsyncIterable` from an array.
```typescript
await fx(toAsync([1, 2, 3, 4]))
.filter(async (a) => a % 2 === 0)
.map(async (a) => a * a)
.reduce(sum);
```
```typescript
await fx([1, 2, 3, 4])
.filter((a) => a % 2 === 0)
.toAsync() // if async function returns
.map(async (a) => a * a)
.reduce(sum);
```
--------------------------------
### Debug Strict Evaluation with tap
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/how-to-debug.md
Use the `tap` function to log intermediate values in strictly-evaluated pipelines. This helps track value changes as the pipeline executes.
```typescript
pipe(
"2021/11/25",
(str) => str.split("/"),
tap((a) => console.log(a)), // ["2021", "11", "25"]
(date) => date.map(Number),
tap((a) => console.log(a)), // [2021, 11, 25]
(date) => date.map((n) => (n === 1 ? 1 : n - 1)),
tap((a) => console.log(a)), // [2020, 10, 24]
(date) => new Date(...date)
);
```
--------------------------------
### Limitations with Iterable and Asynchronous Callbacks
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/to-async.md
Illustrates that `Iterable` types in FxTS do not support asynchronous callback functions or direct handling of `Iterable>`. Attempting to use them will result in errors.
```typescript
const promiseNumbers = function* () {
yield Promise.resolve(1);
yield Promise.resolve(2);
yield Promise.resolve(3);
};
find((num) => Promise.resolve(num === 2), numbers()); // not work
find((num) => num === 2, promiseNumbers()); // not work
```
--------------------------------
### Chaining Style Data Transformation
Source: https://github.com/marpple/fxts/blob/main/website/docs/public/llms.txt
The chaining style provides an alternative to pipe() for data transformations, using method calls on the fx() object.
```typescript
import { fx } from "@fxts/core";
fx([1, 2, 3, 4, 5])
.map(a => a * 2)
.filter(a => a > 4)
.take(2)
.toArray(); // [6, 8]
```
--------------------------------
### Concurrency Error Handling with FxTS Concurrent
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/error-handling.md
Illustrates error handling when using `concurrent` for parallel asynchronous operations. Note that all concurrent operations will be evaluated even if an error occurs early, similar to `Promise.all`.
```typescript
import { concurrent, filter, map, pipe, toArray, toAsync } from "@fxts/core";
const fetchAsyncError = (a) => {
if (a === 3) {
return Promise.reject(`err ${a}`);
}
return a;
};
try {
await pipe(
[
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3), // When this item is evaluated, `map` function throws an error.
Promise.resolve(4), // This item is also evaluated.
Promise.resolve(5), // Is is not evaluated from this item.
Promise.resolve(6),
],
toAsync,
map(fetchAsyncError),
filter((a) => a % 2 === 0),
concurrent(2), // request 2
toArray,
);
} catch (err) {
// handle err
}
```
--------------------------------
### Lazy Function Composition and Strict Evaluation
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/lazy-evaluation.md
Shows how lazy functions in FxTS compose without immediate evaluation, similar to generators. Evaluation is triggered by strict functions like `toArray` or iteration constructs like `for-of`.
```typescript
const squareNums = pipe(
range(Infinity),
map((a) => a * a),
); // not evaluated not yet
const result = pipe(
squareNums,
filter((a) => a % 2 === 0),
take(10),
toArray, // Strict function
);
```
--------------------------------
### Handling Promises with pipe
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/function-composition.md
The `pipe` function automatically handles Promise values, unwrapping them before passing them to the next function. This simplifies asynchronous operations within a composition chain.
```typescript
await pipe(
Promise.resolve(1),
(a /*: Awaited*/) => a + 1,
async (b /*: Awaited*/) => b + 1,
(c /*: Awaited*/) => c + 1,
); // 4
```
--------------------------------
### Debug Lazy Evaluation with peek
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/how-to-debug.md
Employ the `peek` function to inspect intermediate values during lazy evaluation. `peek` allows you to see the actual evaluated values, unlike `tap` in this context.
```typescript
pipe(
range(1, Infinity),
map(addDateFrom(new Date(2000, 0, 1))),
filter(is13thOfFriday),
peek(console.log),
map(formatYYYYMMDD),
peek(console.log),
take(5),
toArray
);
```
--------------------------------
### Optimized Eager Array Evaluation Order
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/lazy-evaluation.md
Shows how placing array-reducing operations like `slice` and `filter` earlier in the chain can minimize traversals in eager evaluation, though still less efficient than lazy evaluation for large datasets.
```typescript
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.filter((a) => a % 2 === 0) // [0, 2, 4, 6, 8]
.slice(0, 2); // [0, 2]
.map((a) => a * a) // [0, 4]
.reduce(sum); // 4
```
--------------------------------
### Strict Functions
Source: https://github.com/marpple/fxts/blob/main/website/docs/public/llms.txt
A collection of strict functions that return a value. These functions are pure and do not have side effects.
```APIDOC
## Strict Functions (returns value)
- [add](https://fxts.dev/api/add)
- [always](https://fxts.dev/api/always)
- [apply](https://fxts.dev/api/apply)
- [average](https://fxts.dev/api/average) (alias: mean)
- [compactObject](https://fxts.dev/api/compactObject)
- [consume](https://fxts.dev/api/consume)
- [countBy](https://fxts.dev/api/countBy)
- [curry](https://fxts.dev/api/curry)
- [delay](https://fxts.dev/api/delay)
- [each](https://fxts.dev/api/each) (alias: forEach)
- [every](https://fxts.dev/api/every)
- [evolve](https://fxts.dev/api/evolve)
- [find](https://fxts.dev/api/find)
- [findIndex](https://fxts.dev/api/findIndex)
- [fromEntries](https://fxts.dev/api/fromEntries)
- [groupBy](https://fxts.dev/api/groupBy)
- [gt](https://fxts.dev/api/gt)
- [gte](https://fxts.dev/api/gte)
- [head](https://fxts.dev/api/head) (alias: first)
- [identity](https://fxts.dev/api/identity)
- [includes](https://fxts.dev/api/includes) (alias: contains)
- [indexBy](https://fxts.dev/api/indexBy)
- [join](https://fxts.dev/api/join)
- [juxt](https://fxts.dev/api/juxt)
- [last](https://fxts.dev/api/last)
- [lt](https://fxts.dev/api/lt)
- [lte](https://fxts.dev/api/lte)
- [max](https://fxts.dev/api/max)
- [memoize](https://fxts.dev/api/memoize)
- [min](https://fxts.dev/api/min)
- [negate](https://fxts.dev/api/negate)
- [noop](https://fxts.dev/api/noop)
- [not](https://fxts.dev/api/not)
- [nth](https://fxts.dev/api/nth)
- [omit](https://fxts.dev/api/omit)
- [omitBy](https://fxts.dev/api/omitBy)
- [partition](https://fxts.dev/api/partition)
- [pick](https://fxts.dev/api/pick)
- [pickBy](https://fxts.dev/api/pickBy)
- [pipe](https://fxts.dev/api/pipe)
- [pipe1](https://fxts.dev/api/pipe1)
- [prop](https://fxts.dev/api/prop)
- [props](https://fxts.dev/api/props)
- [reduce](https://fxts.dev/api/reduce)
- [reduceLazy](https://fxts.dev/api/reduceLazy)
- [resolveProps](https://fxts.dev/api/resolveProps)
- [size](https://fxts.dev/api/size)
- [some](https://fxts.dev/api/some)
- [sort](https://fxts.dev/api/sort)
- [sortBy](https://fxts.dev/api/sortBy)
- [sum](https://fxts.dev/api/sum)
- [tap](https://fxts.dev/api/tap)
- [throwError](https://fxts.dev/api/throwError)
- [throwIf](https://fxts.dev/api/throwIf)
- [toArray](https://fxts.dev/api/toArray)
- [unicodeToArray](https://fxts.dev/api/unicodeToArray)
- [unless](https://fxts.dev/api/unless)
- [when](https://fxts.dev/api/when)
```
--------------------------------
### Type Guard Functions
Source: https://github.com/marpple/fxts/blob/main/website/docs/public/llms.txt
Functions that check the type of a value and return a boolean.
```APIDOC
## Type Guard Functions
- [isArray](https://fxts.dev/api/isArray)
- [isBoolean](https://fxts.dev/api/isBoolean)
- [isDate](https://fxts.dev/api/isDate)
- [isEmpty](https://fxts.dev/api/isEmpty)
- [isNil](https://fxts.dev/api/isNil)
- [isNull](https://fxts.dev/api/isNull)
- [isNumber](https://fxts.dev/api/isNumber)
- [isObject](https://fxts.dev/api/isObject)
- [isString](https://fxts.dev/api/isString)
- [isUndefined](https://fxts.dev/api/isUndefined)
```
--------------------------------
### Sequential Map with Concurrent Filter
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/handle-concurrency.md
Executes asynchronous `map` operations sequentially and then applies `concurrent` to the asynchronous predicate of `filter`, processing up to three filters simultaneously.
```typescript
await pipe(
range(Infinity),
toAsync,
map(fetchApi),
toArray,
filter((a) => delay(100, a % 2 === 0)),
take(3),
concurrent(3),
each(console.log),
);
```
--------------------------------
### Debugging Lazy Evaluation with tap
Source: https://github.com/marpple/fxts/blob/main/website/docs/guide/how-to-debug.md
Using `tap` in a lazy evaluation pipeline logs `IterableIterator` types, making it difficult to trace actual values. This highlights the need for a different debugging approach for lazy pipelines.
```typescript
pipe(
range(1, Infinity),
map(addDateFrom(new Date(2000, 0, 1))),
filter(is13thOfFriday),
tap(console.log), // IterableIterator
map(formatYYYYMMDD),
tap(console.log), // IterableIterator
take(5),
toArray
);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.