### Quick Start: Option and Result Usage Source: https://github.com/3axap4ehko/nalloc/blob/master/README.md Demonstrates basic usage of Option and Result types, including fromNullable, unwrapOr, tryCatch, and match. ```typescript import { Option, Result, ok, err, none, pipe, gen } from 'nalloc'; // Option: the value IS the Option const port = Option.fromNullable(process.env.PORT); const portNum = Option.unwrapOr(port, '3000'); // Result: Ok is the value itself, Err wraps the error const config = Result.tryCatch(() => JSON.parse(raw), () => 'invalid json'); const data = Result.match( config, cfg => cfg, error => ({ fallback: true }) ); ``` -------------------------------- ### Install nalloc Source: https://github.com/3axap4ehko/nalloc/blob/master/README.md Install the nalloc package using npm. ```bash npm install nalloc ``` -------------------------------- ### Quick Start: pipe for Left-to-Right Composition Source: https://github.com/3axap4ehko/nalloc/blob/master/README.md Demonstrates function composition using the 'pipe' utility, allowing for a left-to-right flow of data through a series of operations. ```typescript const userId = pipe( Result.tryCatch(() => JSON.parse(raw)), r => Result.map(r, data => data.userId), r => Result.unwrapOr(r, 0), ); ``` -------------------------------- ### Quick Start: gen for Rust-like ? Operator Source: https://github.com/3axap4ehko/nalloc/blob/master/README.md Utilizes the 'gen' function to enable Rust-like error propagation using the 'yield*' syntax within a generator function. ```typescript const result = gen(function*($) { const a = yield* $(parseNumber('10')); const b = yield* $(parseNumber('5')); return a + b; }); // Result ``` -------------------------------- ### Comparison: Other Libraries vs. nalloc Allocation Source: https://github.com/3axap4ehko/nalloc/blob/master/README.md Illustrates the memory allocation differences between nalloc and other Option/Result libraries, highlighting nalloc's zero-allocation approach for Some and Ok. ```text Other libraries: Some(42) --> { _tag: 'Some', value: 42 } // allocates nalloc: Some(42) --> 42 // zero allocation Other libraries: Ok(data) --> { _tag: 'Ok', value: data } // allocates nalloc: Ok(data) --> data // zero allocation ``` -------------------------------- ### Creating Option Values Source: https://context7.com/3axap4ehko/nalloc/llms.txt Demonstrates how to create Option values from nullable types and Promises, and how to use type guards. ```APIDOC ## Creating Option Values Options represent values that may or may not exist. In nalloc, a `Some` value is the value itself, while `None` is `null` or `undefined`. ### Method N/A (Creation methods) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { Option, none, isSome, isNone } from 'nalloc'; // Create from nullable values const maybePort = Option.fromNullable(process.env.PORT); const maybeNull = Option.fromNullable(null); // None // Type guards if (isSome(maybePort)) { console.log(`Port is: ${maybePort}`); // maybePort is the value itself } if (isNone(maybeNull)) { console.log('Value is missing'); } // Create from Promise (rejection becomes None) const maybeUser = await Option.fromPromise(fetch('/api/user').then(r => r.json())); ``` ### Response #### Success Response (200) N/A (Creation methods) #### Response Example N/A ``` -------------------------------- ### Create Option Values Source: https://context7.com/3axap4ehko/nalloc/llms.txt Demonstrates creating Options from nullable values, using type guards, and creating Options from Promises. ```typescript import { Option, none, isSome, isNone } from 'nalloc'; // Create from nullable values const maybePort = Option.fromNullable(process.env.PORT); const maybeNull = Option.fromNullable(null); // None // Type guards if (isSome(maybePort)) { console.log(`Port is: ${maybePort}`); // maybePort is the value itself } if (isNone(maybeNull)) { console.log('Value is missing'); } // Create from Promise (rejection becomes None) const maybeUser = await Option.fromPromise(fetch('/api/user').then(r => r.json())); ``` -------------------------------- ### Migration from oxide.ts Source: https://github.com/3axap4ehko/nalloc/blob/master/README.md Illustrates the difference in Option and Result mapping between oxide.ts and nalloc, emphasizing nalloc's approach where the value is the Option and Ok is zero-allocation. ```typescript // oxide.ts import { Some, None, Ok, Err } from 'oxide.ts'; const opt = Some(42); opt.map(x => x * 2); const result = Ok(42); result.mapErr(e => new Error(e)); // nalloc - no wrapper objects on the happy path import { Option, Result, ok } from 'nalloc'; Option.map(42, x => x * 2); // 42 is the Option itself const result = ok(42); // zero allocation Result.mapErr(result, e => new Error(e)); ``` -------------------------------- ### Creating Result Values Source: https://context7.com/3axap4ehko/nalloc/llms.txt Demonstrates how to create `Ok` and `Err` values using nalloc's Result functions. ```APIDOC ## Creating Result Values ### Description Represents operations that may succeed (`Ok`) or fail (`Err`). In nalloc, `Ok` values are the raw values themselves, while `Err` wraps the error. This section shows how to create these values and use type guards. ### Method N/A (Utility functions) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { Result, ok, err, isOk, isErr } from 'nalloc'; // Create Ok and Err values const success = ok(42); // Result: Ok(42) - zero allocation const failure = err('not found'); // Result: Err('not found') - wraps error // Type guards if (isOk(success)) { console.log(`Value: ${success}`); // Output: Value: 42 (success IS the value) } if (isErr(failure)) { console.log(`Error: ${failure.error}`); // Output: Error: not found (Access error via .error) } ``` ### Response N/A (These are utility functions operating on input data) ``` -------------------------------- ### Iter.tryCollect / Iter.tryFold / Iter.tryForEach Source: https://context7.com/3axap4ehko/nalloc/llms.txt Result-oriented iteration utilities with early exit on errors. ```APIDOC ## Iter.tryCollect / Iter.tryFold / Iter.tryForEach ### Description Result-oriented iteration utilities with early exit on errors. ### Request Example ```typescript const results = items.map(n => n < 4 ? ok(n * 10) : err(`${n} too large`)); const collected = Iter.tryCollect(results); ``` ``` -------------------------------- ### Option.flatMap / Option.andThen Source: https://context7.com/3axap4ehko/nalloc/llms.txt Chains Option-returning functions, flattening the result. Returns `None` if the input is `None`. ```APIDOC ## Option.flatMap / Option.andThen Chains Option-returning functions, flattening the result. Returns `None` if the input is `None`. ### Method N/A (Utility function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { Option, none } from 'nalloc'; function parsePort(s: string): Option { const n = parseInt(s, 10); return isNaN(n) ? none : n; } function validateRange(n: number): Option { return n >= 1 && n <= 65535 ? n : none; } const port = Option.fromNullable(process.env.PORT); const validPort = Option.flatMap( Option.flatMap(port, parsePort), validateRange ); // Using andThen (alias for flatMap) const result = Option.andThen(port, parsePort); ``` ### Response #### Success Response (200) N/A (Utility function) #### Response Example N/A ``` -------------------------------- ### Option.match Source: https://context7.com/3axap4ehko/nalloc/llms.txt Pattern matches on an Option, providing distinct handlers for `Some` and `None` cases. ```APIDOC ## Option.match Pattern matches on an Option, handling both `Some` and `None` cases. ### Method N/A (Utility function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { Option, none } from 'nalloc'; const maybeUser = Option.fromNullable(getUser()); const greeting = Option.match( maybeUser, user => `Hello, ${user.name}!`, () => 'Hello, guest!' ); // Use for complex branching logic const result = Option.match( Option.fromNullable(process.env.MODE), mode => { if (mode === 'production') return { debug: false, optimize: true }; return { debug: true, optimize: false }; }, () => ({ debug: true, optimize: false }) ); ``` ### Response #### Success Response (200) N/A (Utility function) #### Response Example N/A ``` -------------------------------- ### Option.unwrap / Option.unwrapOr / Option.expect Source: https://context7.com/3axap4ehko/nalloc/llms.txt Extracts the value from an Option, with different strategies for handling `None`. ```APIDOC ## Option.unwrap / Option.unwrapOr / Option.expect Extracts the value from an Option, with different strategies for handling `None`. ### Method N/A (Utility functions) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { Option, none } from 'nalloc'; const maybeValue = Option.fromNullable(process.env.CONFIG); // unwrap: throws if None try { const value = Option.unwrap(maybeValue); } catch (e) { console.log('Value was missing'); } // unwrapOr: returns default if None const config = Option.unwrapOr(maybeValue, 'default-config'); // unwrapOrElse: computes default lazily const computed = Option.unwrapOrElse(maybeValue, () => computeDefault()); // expect: throws with custom message const required = Option.expect(maybeValue, 'CONFIG environment variable is required'); ``` ### Response #### Success Response (200) N/A (Utility functions) #### Response Example N/A ``` -------------------------------- ### Rust API Equivalents in nalloc Source: https://github.com/3axap4ehko/nalloc/blob/master/README.md Demonstrates how common Rust Option and Result operations like map, andThen, and unwrapOr are implemented in nalloc. ```typescript import { Option, Result, ok, err, none, gen } from 'nalloc'; // Rust: Some(42).map(|x| x * 2) Option.map(42, x => x * 2); // Rust: Ok(42).and_then(|x| if x > 0 { Ok(x) } else { Err("negative") }) Result.andThen(ok(42), x => x > 0 ? ok(x) : err('negative')); // Rust: result.unwrap_or(0) Result.unwrapOr(result, 0); ``` -------------------------------- ### Option.filterMap and Option.findMap for Collections Source: https://context7.com/3axap4ehko/nalloc/llms.txt Use filterMap to map and filter collection elements in one pass, collecting only Some values. Use findMap to find the first element that maps to a Some value. Both require importing Option from 'nalloc'. ```typescript import { Option, none } from 'nalloc'; const users = [ { name: 'Alice', age: 25, active: true }, { name: 'Bob', age: 17, active: false }, { name: 'Charlie', age: 30, active: true }, ]; // filterMap: map and filter in one pass, collecting only Some values const activeAdultNames = Option.filterMap(users, user => user.active && user.age >= 18 ? user.name : none ); // ['Alice', 'Charlie'] // findMap: find first element that maps to Some const firstAdult = Option.findMap(users, user => user.age >= 18 ? user : none ); // { name: 'Alice', age: 25, active: true } ``` -------------------------------- ### Process streams with Iter utilities Source: https://github.com/3axap4ehko/nalloc/blob/master/README.md Iter provides tools for safe iteration and folding over collections that may produce errors. ```ts import { Iter } from 'nalloc'; // Safe iteration: wraps throws as Err, values as Ok for (const result of Iter.safeIter(riskyIterator)) { if (isOk(result)) handleValue(result); else handleError(result.error); } // mapWhile: yields mapped values while fn returns Some const taken = [...Iter.mapWhile([1, 2, 3, 4, 5], n => n < 4 ? n * 10 : null )]; // [10, 20, 30] // tryCollect: collect Results into Result const collected = Iter.tryCollect(results); // Ok([1, 2, 3]) or first Err // tryFold: fold with early exit on Err const sum = Iter.tryFold([1, 2, 3], 0, (acc, n) => ok(acc + n)); // tryForEach: iterate with early exit on Err Iter.tryForEach(items, item => processItem(item)); ``` -------------------------------- ### Result.zip / Result.zipWith Source: https://context7.com/3axap4ehko/nalloc/llms.txt Combine two Results into a tuple or with a combining function. ```APIDOC ## Result.zip / Result.zipWith ### Description Combine two Results into a tuple or with a combining function. ### Method Static methods on Result ### Endpoint N/A (Utility functions) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { Result, ok, err } from 'nalloc'; const userResult = fetchUser(id); const postsResult = fetchPosts(id); // zip: Combine into tuple if both Ok const combined = Result.zip(userResult, postsResult); // Ok([user, posts]) or first Err // zipWith: Combine with a function const profile = Result.zipWith( userResult, postsResult, (user, posts) => ({ ...user, posts }) ); // Ok({ ...user, posts }) or first Err ``` ### Response #### Success Response (200) N/A (Return value is a Result containing the combined data) #### Response Example N/A ``` -------------------------------- ### Migration from neverthrow Source: https://github.com/3axap4ehko/nalloc/blob/master/README.md Shows the equivalent usage of Result.map in nalloc compared to neverthrow, emphasizing nalloc's function-based API and zero-allocation for Ok. ```typescript // neverthrow import { ok, err, Result } from 'neverthrow'; const result: Result = ok(42); result.map(x => x * 2); // nalloc - same concepts, faster execution import { Result, ok, err } from 'nalloc'; const result = ok(42); // zero allocation Result.map(result, x => x * 2); // function-based API ``` -------------------------------- ### Chain Options with flatMap and andThen Source: https://context7.com/3axap4ehko/nalloc/llms.txt Chains functions that return Options, flattening the result and propagating None. ```typescript import { Option, none } from 'nalloc'; function parsePort(s: string): Option { const n = parseInt(s, 10); return isNaN(n) ? none : n; } function validateRange(n: number): Option { return n >= 1 && n <= 65535 ? n : none; } const port = Option.fromNullable(process.env.PORT); const validPort = Option.flatMap( Option.flatMap(port, parsePort), validateRange ); // Using andThen (alias for flatMap) const result = Option.andThen(port, parsePort); ``` -------------------------------- ### Creating Result Values with ok, err, isOk, isErr Source: https://context7.com/3axap4ehko/nalloc/llms.txt Create Ok and Err values using the `ok` and `err` functions. Use `isOk` and `isErr` as type guards to safely access values or errors. Requires importing from 'nalloc'. ```typescript import { Result, ok, err, isOk, isErr } from 'nalloc'; // Create Ok and Err values const success = ok(42); // Ok(42) - zero allocation const failure = err('not found'); // Err('not found') - wraps error // Type guards if (isOk(success)) { console.log(`Value: ${success}`); // success IS the value (42) } if (isErr(failure)) { console.log(`Error: ${failure.error}`); // Access error via .error } ``` -------------------------------- ### Iter Utilities Source: https://github.com/3axap4ehko/nalloc/blob/master/README.md Utilities for working with iterators, including safe iteration, mapping, and collection of fallible operations. ```APIDOC ## Iter Iterator utilities for working with fallible iteration and Result streams. ### Usage Examples ```ts import { Iter } from 'nalloc'; // Safe iteration: wraps throws as Err, values as Ok for (const result of Iter.safeIter(riskyIterator)) { if (isOk(result)) handleValue(result); else handleError(result.error); } // mapWhile: yields mapped values while fn returns Some const taken = [...Iter.mapWhile([1, 2, 3, 4, 5], n => n < 4 ? n * 10 : null )]; // [10, 20, 30] // tryCollect: collect Results into Result const collected = Iter.tryCollect(results); // Ok([1, 2, 3]) or first Err // tryFold: fold with early exit on Err const sum = Iter.tryFold([1, 2, 3], 0, (acc, n) => ok(acc + n)); // tryForEach: iterate with early exit on Err Iter.tryForEach(items, item => processItem(item)); ``` ``` -------------------------------- ### Result.all / Result.any / Result.collect Source: https://context7.com/3axap4ehko/nalloc/llms.txt Combine multiple Results into one. ```APIDOC ## Result.all / Result.any / Result.collect ### Description Combine multiple Results into one. ### Method Static methods on Result ### Endpoint N/A (Utility functions) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { Result, ok, err } from 'nalloc'; const results = [ Result.tryCatch(() => parseA(inputA)), Result.tryCatch(() => parseB(inputB)), Result.tryCatch(() => parseC(inputC)), ]; // all/collect: Succeeds only if ALL are Ok, fails on first Err const allParsed = Result.all(results); // Ok([a, b, c]) or Err(firstError) // any: Succeeds if ANY is Ok, fails only if ALL are Err const anyParsed = Result.any(results); // Ok(firstSuccess) or Err([all, errors]) // collectAll: Collects all errors if any fail const collected = Result.collectAll(results); // Ok([a, b, c]) or Err([all, errors]) // partition: Split into successes and failures const [successes, failures] = Result.partition(results); ``` ### Response #### Success Response (200) N/A (Return value is a Result containing aggregated results or errors) #### Response Example N/A ``` -------------------------------- ### Migration from fp-ts Source: https://github.com/3axap4ehko/nalloc/blob/master/README.md Compares Option.map usage between fp-ts and nalloc, highlighting nalloc's built-in pipe and the value itself being the Option. ```typescript // fp-ts import { pipe } from 'fp-ts/function'; import * as O from 'fp-ts/Option'; pipe(O.some(42), O.map(x => x * 2)); // nalloc - simpler, faster import { Option, pipe } from 'nalloc'; pipe(42, v => Option.map(v, x => x * 2)); // built-in pipe, value IS the Option ``` -------------------------------- ### Option.okOr / Option.okOrElse Source: https://context7.com/3axap4ehko/nalloc/llms.txt Converts an Option to a Result, providing an error value for the `None` case. ```APIDOC ## Option.okOr / Option.okOrElse ### Description Converts an `Option` to a `Result`. If the `Option` is `Some`, it returns an `Ok` containing the value. If the `Option` is `None`, it returns an `Err` with a provided error value (`okOr`) or a lazily computed error (`okOrElse`). ### Method N/A (Utility functions) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { Option, Result, none } from 'nalloc'; // Assume params.id is potentially undefined const params = { id: undefined }; const maybeId = Option.fromNullable(params.id); // okOr: use a static error value const result = Option.okOr(maybeId, 'ID is required'); // Result - if maybeId is None, result is Err('ID is required') // okOrElse: compute error lazily class ValidationError extends Error { constructor(message: string) { super(message); this.name = 'ValidationError'; } } const result2 = Option.okOrElse(maybeId, () => new ValidationError('Missing ID')); // Result - if maybeId is None, result2 is Err(new ValidationError('Missing ID')) ``` ### Response N/A (These are utility functions operating on input data) ``` -------------------------------- ### Migration from ts-results Source: https://github.com/3axap4ehko/nalloc/blob/master/README.md Compares Result.map and Option.unwrapOr usage between ts-results and nalloc, noting nalloc's lack of wrapper objects for Ok and the value being the Option. ```typescript // ts-results import { Ok, Err, Some, None } from 'ts-results'; const result = new Ok(42); result.map(x => x * 2); const opt = Some(42); opt.unwrapOr(0); // nalloc - same safety, zero allocations import { Option, Result, ok } from 'nalloc'; const result = ok(42); // no wrapper Result.map(result, x => x * 2); Option.unwrapOr(42, 0); // value IS the Option ``` -------------------------------- ### Result.wrap / Result.toThrowable Source: https://context7.com/3axap4ehko/nalloc/llms.txt Functions to convert between throwing functions and Result-returning functions. ```APIDOC ## Result.wrap / Result.toThrowable ### Description `Result.wrap` converts a standard JavaScript function that might throw into a function that returns a `Result`. `Result.toThrowable` does the opposite, converting a `Result`-returning function into one that throws on `Err`. ### Method N/A (Utility functions) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { Result, ok, err } from 'nalloc'; // wrap: Convert throwing function to Result-returning const safeParse = Result.wrap(JSON.parse); const parseSuccess = safeParse('{"a":1}'); // Result: Ok({a: 1}) const parseFailure = safeParse('invalid'); // Result: Err(SyntaxError: Unexpected token...) // With error transformer const safeParseTyped = Result.wrap( JSON.parse, e => ({ type: 'json_error' as const, cause: e }) ); const typedFailure = safeParseTyped('invalid'); // Result: Err({ type: 'json_error', cause: SyntaxError(...) }) // toThrowable: Convert Result-returning to throwing (for library boundaries) interface User { id: string; name: string; } class NotFoundError extends Error { constructor(id: string) { super(`User ${id} not found`); this.name = 'NotFoundError'; } } function findUser(id: string): Result { // Dummy implementation: returns Ok for '123', Err otherwise if (id === '123') { return ok({ id: '123', name: 'Alice' }); } else { return err(new NotFoundError(id)); } } const throwingFind = Result.toThrowable(findUser); // Use in contexts that expect exceptions (Express, Drizzle, etc.) try { const user = throwingFind('123'); // user is { id: '123', name: 'Alice' } console.log('User found:', user); } catch (e) { // This block is not reached for id '123' if (e instanceof NotFoundError) { console.error('Caught NotFoundError:', e.message); } } try { throwingFind('456'); } catch (e) { // This block is reached for id '456' if (e instanceof NotFoundError) { console.error('Caught NotFoundError:', e.message); // Output: Caught NotFoundError: User 456 not found } } ``` ### Response N/A (These are utility functions) ``` -------------------------------- ### Generator Do-Notation Source: https://context7.com/3axap4ehko/nalloc/llms.txt Use gen or genAsync to implement Rust-like early returns on errors within synchronous or asynchronous flows. ```typescript import { gen, genAsync, ok, err } from 'nalloc'; // Synchronous generator const result = gen(function*($) { const config = yield* $(parseConfig(rawConfig)); const validated = yield* $(validateConfig(config)); const db = yield* $(connectToDb(validated.dbUrl)); return { config: validated, db }; }); // Result<{ config: ValidConfig; db: Database }, ParseError | ValidationError | DbError> // Async generator const asyncResult = await genAsync(async function*($) { const user = yield* $(await Result.fromPromise(fetchUser(id))); const posts = yield* $(await Result.fromPromise(fetchPosts(user.id))); const comments = yield* $(await Result.fromPromise(fetchComments(posts[0].id))); return { user, posts, comments }; }); // Promise> ``` -------------------------------- ### Pattern Match with match Source: https://context7.com/3axap4ehko/nalloc/llms.txt Handles both Some and None cases using pattern matching. ```typescript import { Option, none } from 'nalloc'; const maybeUser = Option.fromNullable(getUser()); const greeting = Option.match( maybeUser, user => `Hello, ${user.name}!`, () => 'Hello, guest!' ); // Use for complex branching logic const result = Option.match( Option.fromNullable(process.env.MODE), mode => { if (mode === 'production') return { debug: false, optimize: true }; return { debug: true, optimize: false }; }, () => ({ debug: true, optimize: false }) ); ``` -------------------------------- ### Result.flatMap and Result.andThen for Chaining Operations Source: https://context7.com/3axap4ehko/nalloc/llms.txt Chain Result-returning functions sequentially. Operations short-circuit and return the first Err encountered. Requires importing Result from 'nalloc'. ```typescript import { Result, ok, err } from 'nalloc'; function parseConfig(raw: string): Result { return Result.tryCatch( () => JSON.parse(raw), () => ({ type: 'parse' as const }) ); } function validateConfig(config: Config): Result { if (!config.host) return err({ type: 'validation' as const, field: 'host' }); return ok(config as ValidConfig); } // Chain operations - stops at first error const validConfig = Result.flatMap( parseConfig(rawInput), validateConfig ); // Result // Using andThen (alias) const result = Result.andThen(parseConfig(input), validateConfig); ``` -------------------------------- ### Result.unwrap / Result.unwrapOr / Result.expect Source: https://context7.com/3axap4ehko/nalloc/llms.txt Extracts the Ok value from a Result with different error handling strategies. ```APIDOC ## Result.unwrap / Result.unwrapOr / Result.expect ### Description Extracts the Ok value from a Result with different error handling strategies. ### Method Static methods on Result ### Endpoint N/A (Utility functions) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { Result, ok, err } from 'nalloc'; const result = Result.tryCatch(() => JSON.parse(input)); // unwrap: throws the error if Err const data = Result.unwrap(result); // throws if Err // unwrapOr: returns default if Err const dataOrDefault = Result.unwrapOr(result, { fallback: true }); // unwrapOrElse: computes default from error const dataOrComputed = Result.unwrapOrElse(result, error => { console.error('Parse failed:', error); return getDefaultConfig(); }); // expect: throws with custom message prefix const required = Result.expect(result, 'Config parse failed'); ``` ### Response #### Success Response (200) N/A (Return value is the unwrapped Ok value or a default value, or throws an error) #### Response Example N/A ``` -------------------------------- ### Type Guards and Assertions Source: https://context7.com/3axap4ehko/nalloc/llms.txt Utilities for type narrowing and runtime validation. ```APIDOC ## Type Guards and Assertions ### Description Various utilities for type narrowing and runtime validation. ### Request Example ```typescript if (isOk(result)) { // result is the Ok value itself } if (isErr(result)) { // result.error contains the error } ``` ``` -------------------------------- ### Option.filterMap / Option.findMap Source: https://context7.com/3axap4ehko/nalloc/llms.txt Utility functions for mapping and filtering collections with Option types. ```APIDOC ## Option.filterMap / Option.findMap ### Description Utility functions for working with collections of values using Option types. `filterMap` maps and filters in one pass, collecting only `Some` values. `findMap` finds the first element that maps to `Some`. ### Method N/A (Utility functions) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { Option, none } from 'nalloc'; const users = [ { name: 'Alice', age: 25, active: true }, { name: 'Bob', age: 17, active: false }, { name: 'Charlie', age: 30, active: true }, ]; // filterMap example const activeAdultNames = Option.filterMap(users, user => user.active && user.age >= 18 ? user.name : none ); // Result: ['Alice', 'Charlie'] // findMap example const firstAdult = Option.findMap(users, user => user.age >= 18 ? user : none ); // Result: { name: 'Alice', age: 25, active: true } ``` ### Response N/A (These are utility functions operating on input data) ``` -------------------------------- ### Result.map, Result.mapErr, and Result.bimap for Transformations Source: https://context7.com/3axap4ehko/nalloc/llms.txt Transform values within a Result. Use `map` for Ok values, `mapErr` for Err values, and `bimap` to transform both. Requires importing Result from 'nalloc'. ```typescript import { Result, ok, err } from 'nalloc'; const result = Result.tryCatch(() => JSON.parse(input)); // map: Transform Ok value, leave Err unchanged const ids = Result.map(result, data => data.ids); // mapErr: Transform Err value, leave Ok unchanged const withMessage = Result.mapErr(result, e => `Parse failed: ${e}`); // bimap: Transform both Ok and Err const normalized = Result.bimap( result, data => data.value.toUpperCase(), error => ({ code: 'PARSE_ERROR', original: error }) ); ``` -------------------------------- ### Iter.safeIter Source: https://context7.com/3axap4ehko/nalloc/llms.txt Wraps an iterable so exceptions become Err values instead of throwing. ```APIDOC ## Iter.safeIter ### Description Wraps an iterable so exceptions become `Err` values instead of throwing. ### Request Example ```typescript for (const result of Iter.safeIter(riskyGenerator())) { if (isOk(result)) { console.log('Got value:', result); } else { console.log('Got error:', result.error); } } ``` ``` -------------------------------- ### gen / genAsync - Generator Do-Notation Source: https://context7.com/3axap4ehko/nalloc/llms.txt Rust-like `?` operator using generators. Provides early return on errors while preserving type information. ```APIDOC ## gen / genAsync - Generator Do-Notation ### Description Rust-like `?` operator using generators. Provides early return on errors while preserving type information. ### Method Static methods `gen` and `genAsync` on the `nalloc` import. ### Endpoint N/A (Utility functions) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { gen, genAsync, ok, err } from 'nalloc'; // Synchronous generator const result = gen(function*($) { const config = yield* $(parseConfig(rawConfig)); const validated = yield* $(validateConfig(config)); const db = yield* $(connectToDb(validated.dbUrl)); return { config: validated, db }; }); // Result<{ config: ValidConfig; db: Database }, ParseError | ValidationError | DbError> // Async generator const asyncResult = await genAsync(async function*($) { const user = yield* $(await Result.fromPromise(fetchUser(id))); const posts = yield* $(await Result.fromPromise(fetchPosts(user.id))); const comments = yield* $(await Result.fromPromise(fetchComments(posts[0].id))); return { user, posts, comments }; }); // Promise> ``` ### Response #### Success Response (200) N/A (Return value is a Result or a Promise of a Result) #### Response Example N/A ``` -------------------------------- ### Result.tryCatch Source: https://context7.com/3axap4ehko/nalloc/llms.txt Wraps a throwing function, catching exceptions and converting them to `Err` values. ```APIDOC ## Result.tryCatch ### Description Wraps a function that might throw an error. If the function executes successfully, `Result.tryCatch` returns an `Ok` with the function's return value. If an error is thrown, it returns an `Err` containing the caught error. An optional error transformer function can be provided to modify the error before it's wrapped in `Err`. ### Method N/A (Utility function) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { Result } from 'nalloc'; // Basic usage - catches any thrown error const parsed = Result.tryCatch(() => JSON.parse('{"valid": true}')); // Result: Ok({ valid: true }) const invalid = Result.tryCatch(() => JSON.parse('not json')); // Result: Err(SyntaxError: Unexpected token...) // With error transformer const rawConfig = '{ "host": "localhost" }'; // Assume this is a string const config = Result.tryCatch( () => JSON.parse(rawConfig), error => ({ code: 'PARSE_ERROR', message: String(error) }) ); // Result: Ok({ host: 'localhost' }) or Err({ code: 'PARSE_ERROR', message: '...' }) // Async variant example (using fetch and fromPromise, conceptually similar to tryCatch for async) // const data = await Result.fromPromise( // fetch('/api/data').then(r => r.json()), // e => new NetworkError(String(e)) // ); ``` ### Response N/A (This is a utility function) ``` -------------------------------- ### Result.fromSchema Source: https://context7.com/3axap4ehko/nalloc/llms.txt Validates values using Standard Schema v1 compatible libraries (Zod, Valibot, ArkType, etc.). ```APIDOC ## Result.fromSchema ### Description Validates values using Standard Schema v1 compatible libraries (Zod, Valibot, ArkType, etc.). ### Method Static method on Result ### Endpoint N/A (Utility function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { Result } from 'nalloc'; import { z } from 'zod'; const userSchema = z.object({ name: z.string().min(1), email: z.string().email(), age: z.number().int().positive(), }); const result = Result.fromSchema(userSchema, input); // Result<{ name: string; email: string; age: number }, readonly SchemaIssue[]> if (Result.isOk(result)) { console.log('Valid user:', result); } else { console.log('Validation errors:', result.error); } ``` ### Response #### Success Response (200) N/A (Return value is a Result containing the validated data or schema issues) #### Response Example N/A ``` -------------------------------- ### Option.okOr and Option.okOrElse for Result Conversion Source: https://context7.com/3axap4ehko/nalloc/llms.txt Convert an Option to a Result. okOr uses a static error value for the None case, while okOrElse computes the error lazily. Both require importing Option and Result from 'nalloc'. ```typescript import { Option, Result, none } from 'nalloc'; const maybeId = Option.fromNullable(params.id); // okOr: use a static error value const result = Option.okOr(maybeId, 'ID is required'); // Result // okOrElse: compute error lazily const result2 = Option.okOrElse(maybeId, () => new ValidationError('Missing ID')); // Result ``` -------------------------------- ### Result.flatMap / Result.andThen Source: https://context7.com/3axap4ehko/nalloc/llms.txt Chains Result-returning functions, short-circuiting execution if an `Err` is encountered. ```APIDOC ## Result.flatMap / Result.andThen ### Description These functions are used for chaining operations where each operation returns a `Result`. If a previous operation resulted in an `Err`, subsequent operations are skipped (short-circuiting), and the `Err` is propagated. `flatMap` and `andThen` are aliases for the same functionality. ### Method N/A (Utility functions) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { Result, ok, err } from 'nalloc'; interface Config { host?: string; port?: number; } interface ParseError { type: 'parse'; } interface ValidationError { type: 'validation'; field: string; } interface ValidConfig { host: string; port: number; } function parseConfig(raw: string): Result { try { const parsed = JSON.parse(raw); if (typeof parsed !== 'object' || parsed === null) { return err({ type: 'parse' }); } return ok(parsed as Config); } catch { return err({ type: 'parse' }); } } function validateConfig(config: Config): Result { if (!config.host) return err({ type: 'validation', field: 'host' }); if (typeof config.port !== 'number') return err({ type: 'validation', field: 'port' }); return ok(config as ValidConfig); } // Chain operations - stops at first error const rawInput1 = '{"host": "localhost", "port": 8080}'; const validConfig1 = Result.flatMap(parseConfig(rawInput1), validateConfig); // Result: Ok({ host: 'localhost', port: 8080 }) const rawInput2 = '{"port": 8080}'; // Missing host const validConfig2 = Result.flatMap(parseConfig(rawInput2), validateConfig); // Result: Err({ type: 'validation', field: 'host' }) const rawInput3 = 'invalid json'; const validConfig3 = Result.flatMap(parseConfig(rawInput3), validateConfig); // Result: Err({ type: 'parse' }) // Using andThen (alias) const result = Result.andThen(parseConfig(rawInput1), validateConfig); // Result: Ok({ host: 'localhost', port: 8080 }) ``` ### Response N/A (These are utility functions) ``` -------------------------------- ### safeTry / safeTryAsync Source: https://context7.com/3axap4ehko/nalloc/llms.txt Imperative error handling with unwrap, catching thrown errors. ```APIDOC ## safeTry / safeTryAsync ### Description Imperative error handling with unwrap, catching thrown errors. ### Method Static methods `safeTry` and `safeTryAsync` on the `nalloc` import. ### Endpoint N/A (Utility functions) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { Result, safeTry, safeTryAsync, unwrap, ok, err } from 'nalloc'; // safeTry catches errors thrown by unwrap const result = safeTry(() => { const a = unwrap(parseNumber('10')); // throws if Err const b = unwrap(parseNumber('5')); return a + b; }); // Ok(15) or Err(thrown error) // Async version const asyncResult = await safeTryAsync(async () => { const user = unwrap(await fetchUser(id)); const posts = unwrap(await fetchPosts(user.id)); return { user, posts }; }); ``` ### Response #### Success Response (200) N/A (Return value is a Result containing the computed value or the caught error) #### Response Example N/A ``` -------------------------------- ### Option.map Source: https://context7.com/3axap4ehko/nalloc/llms.txt Transforms the value inside a `Some` using a mapping function. If the Option is `None`, it remains `None`. ```APIDOC ## Option.map Transforms the value inside a `Some`, or returns `None` if the option is empty. ### Method N/A (Utility function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { Option } from 'nalloc'; const port = Option.fromNullable(process.env.PORT); const portNumber = Option.map(port, p => parseInt(p, 10)); const doubled = Option.map(portNumber, n => n * 2); // Chaining multiple transformations const result = Option.map( Option.map(port, p => parseInt(p, 10)), n => n * 2 ); // None propagates through maps const fromNone = Option.map(null, x => x * 2); // None ``` ### Response #### Success Response (200) N/A (Utility function) #### Response Example N/A ``` -------------------------------- ### Extract Values with unwrap and expect Source: https://context7.com/3axap4ehko/nalloc/llms.txt Extracts values from an Option using various strategies for handling None cases. ```typescript import { Option, none } from 'nalloc'; const maybeValue = Option.fromNullable(process.env.CONFIG); // unwrap: throws if None try { const value = Option.unwrap(maybeValue); } catch (e) { console.log('Value was missing'); } // unwrapOr: returns default if None const config = Option.unwrapOr(maybeValue, 'default-config'); // unwrapOrElse: computes default lazily const computed = Option.unwrapOrElse(maybeValue, () => computeDefault()); // expect: throws with custom message const required = Option.expect(maybeValue, 'CONFIG environment variable is required'); ``` -------------------------------- ### Combining Multiple Results Source: https://context7.com/3axap4ehko/nalloc/llms.txt Aggregate multiple results using all, any, collectAll, or partition to manage collections of operations. ```typescript import { Result, ok, err } from 'nalloc'; const results = [ Result.tryCatch(() => parseA(inputA)), Result.tryCatch(() => parseB(inputB)), Result.tryCatch(() => parseC(inputC)), ]; // all/collect: Succeeds only if ALL are Ok, fails on first Err const allParsed = Result.all(results); // Ok([a, b, c]) or Err(firstError) // any: Succeeds if ANY is Ok, fails only if ALL are Err const anyParsed = Result.any(results); // Ok(firstSuccess) or Err([all, errors]) // collectAll: Collects all errors if any fail const collected = Result.collectAll(results); // Ok([a, b, c]) or Err([all, errors]) // partition: Split into successes and failures const [successes, failures] = Result.partition(results); ``` -------------------------------- ### NonEmpty Source: https://context7.com/3axap4ehko/nalloc/llms.txt Proves at the type level that an array has at least one element. ```APIDOC ## NonEmpty ### Description Proves at the type level that an array has at least one element, with zero runtime overhead. ### Request Example ```typescript if (NonEmpty.isNonEmpty(values)) { const first: number = values[0]; } ``` ``` -------------------------------- ### Pattern Matching on Results Source: https://context7.com/3axap4ehko/nalloc/llms.txt Use Result.match to handle both Ok and Err cases, or to perform control flow based on the result state. ```typescript import { Result, ok, err } from 'nalloc'; const result = Result.tryCatch(() => fetchData()); const response = Result.match( result, data => ({ status: 200, body: data }), error => ({ status: 500, body: { error: String(error) } }) ); // Use for control flow Result.match( validateInput(input), valid => processValid(valid), errors => logErrors(errors) ); ``` -------------------------------- ### Extracting Values from Results Source: https://context7.com/3axap4ehko/nalloc/llms.txt Extract values using unwrap, unwrapOr, unwrapOrElse, or expect to handle errors with different strategies. ```typescript import { Result, ok, err } from 'nalloc'; const result = Result.tryCatch(() => JSON.parse(input)); // unwrap: throws the error if Err const data = Result.unwrap(result); // throws if Err // unwrapOr: returns default if Err const dataOrDefault = Result.unwrapOr(result, { fallback: true }); // unwrapOrElse: computes default from error const dataOrComputed = Result.unwrapOrElse(result, error => { console.error('Parse failed:', error); return getDefaultConfig(); }); // expect: throws with custom message prefix const required = Result.expect(result, 'Config parse failed'); ``` -------------------------------- ### Result.wrap for Converting Throwing Functions Source: https://context7.com/3axap4ehko/nalloc/llms.txt Convert a function that might throw into one that returns a Result. Use Result.wrap for this purpose. An optional error transformer can be provided. Requires importing Result from 'nalloc'. ```typescript import { Result, ok, err } from 'nalloc'; // wrap: Convert throwing function to Result-returning const safeParse = Result.wrap(JSON.parse); safeParse('{"a":1}'); // Ok({a: 1}) safeParse('invalid'); // Err(SyntaxError) // With error transformer const safeParseTyped = Result.wrap( JSON.parse, e => ({ type: 'json_error' as const, cause: e }) ); // toThrowable: Convert Result-returning to throwing (for library boundaries) function findUser(id: string): Result { // ... returns Result } const throwingFind = Result.toThrowable(findUser); // Use in contexts that expect exceptions (Express, Drizzle, etc.) try { const user = throwingFind('123'); } catch (e) { // e is NotFoundError } ``` -------------------------------- ### pipe Source: https://context7.com/3axap4ehko/nalloc/llms.txt Threads a value through a sequence of functions left-to-right for clean data transformations. ```APIDOC ## pipe ### Description Threads a value through a sequence of functions left-to-right for clean data transformations. ### Request Example ```typescript const userId = pipe( Result.tryCatch(() => JSON.parse(rawInput)), r => Result.map(r, data => data.userId), r => Result.flatMap(r, id => id > 0 ? ok(id) : err('invalid id')), r => Result.unwrapOr(r, 0) ); ``` ```