ts-belt Documentation

repository·master·Indexed 22 days ago

https://github.com/mobily/ts-belt

A fast, modern, and practical utility library for Functional Programming (FP) in TypeScript. It provides immutable, tree-shakeable, data-first utilities across namespaces for Arrays (A), Booleans (B), Numbers (N), Objects (D), Strings (S), Guards (G), Options (O), Results (R), and Functions (F), along with pipe and flow for value and function composition.

Tokens
29.8K
Snippets
126
Records
159
Agent score
77%

What's inside @mobily/ts-belt

  1. What is ts-belt?

    master

    ts-belt is a high-performance functional programming library for TypeScript and Flow. It is designed to combine the developer experience of a data-first approach with the performance of highly optimized JavaScript.

    Key characteristics include:

    • High Performance: Built using ReScript and the Belt standard library, generating highly performant JavaScript code.
    • Data-First Approach: Provides a more readable and natural developer experience compared to data-last libraries.
    • Type Safety: Leverages Option and Result types to help write safer code, with excellent TypeScript and Flow support.
    • Immutability: All functions return immutable data, ensuring no side-effects.
    • Modern Tooling: The library is tree-shakeable and fully documented.
  2. Performance benchmarks for @mobily/ts-belt (MacBook Pro M1 Max)

    master

    Benchmarks conducted on a MacBook Pro (M1 Max, 64 GB, Node v16.13.0) demonstrate that @mobily/ts-belt consistently outperforms other functional programming libraries like remeda, ramda, rambda, lodash/fp, and native implementations across various common operations.

    Key performance highlights include:

    • map-filter-reduce chains
    • deepFlat-uniq-groupBy sequences
    • sort (both standalone and within a pipe)
    • unzip (both standalone and within a pipe)
    • flat (both standalone and within a pipe)
    • dropWhile and takeWhile (both standalone and within a pipe)
    • difference
  3. Use Object (Dict) utility functions

    master
    The Dict module provides a collection of utility functions for working with Object types in TypeScript. These utilities allow for functional-style manipulation of objects, similar to how Array utilities work for lists. Common operations include mapping, filtering, and transforming key-value pairs within an object.
  4. Performance benchmarks for @mobily/ts-belt

    master

    Historical benchmarks (v3.7.0 on MacBook Air 2020) demonstrate that @mobily/ts-belt is highly optimized for performance, frequently outperforming rambda, lodash/fp, ramda, remeda, and native implementations across various common operations.

    Key performance highlights include:

    • map/filter/reduce: Faster than rambda, lodash/fp, and native.
    • deepFlat (inside pipe): Significantly faster than remeda, ramda, rambda, and lodash/fp.
    • reduce (single call and inside pipe): Outperforms remeda, ramda, rambda, lodash/fp, and native.
    • reject (inside pipe): Faster than remeda, ramda, rambda, and lodash/fp.
    • intersperse (single call and inside pipe): Faster than ramda and rambda.
    • fromPairs (single call and inside pipe): Faster than remeda, ramda, rambda, lodash/fp, and native.
    • groupBy (single call and inside pipe): Faster than remeda, ramda, rambda, and lodash/fp.
  5. Understand the Option type

    master

    In TS Belt, the Option<T> type is used to represent the existence or nonexistence of a value. It is a type alias that wraps a value T and allows it to be undefined or null to represent the absence of a value (often referred to as None).

    Mandatory Configuration: To use Option safely and effectively, you must enable noUncheckedIndexedAccess in your tsconfig.json. This ensures that accessing elements in arrays or objects correctly results in undefined rather than a potentially incorrect type, allowing the Option utilities to work as intended.

    type Option<T> = T | undefined | null
  6. Understand the difference between pipe and flow

    master

    While both functions perform left-to-right composition, they serve different purposes:

    1. pipe(value, fn1, fn2, ...): Operates on a value. It executes the transformations immediately and returns the final result. The first argument must be the data you want to process.
    2. flow(fn1, fn2, ...): Operates on functions. It returns a new function that represents the composed pipeline. The first function can take multiple arguments, but all following functions must be unary.

    Example of them working together:

    // 1. Define a reusable transformation pipeline using flow
    const clean = flow(S.removeAll('X'), S.toLowerCase)
    
    // 2. Apply that pipeline to a value using pipe
    const value = pipe(
      ['HellXXXo', 'wOrXXXLd'],
      A.map(clean),
      A.join(' ')
    )
    const clean = flow(S.removeAll('X'), S.toLowerCase)
    const value = pipe(
      ['HellXXXo', 'wOrXXXLd'],
      A.map(clean),
      A.join(' ')
    )
  7. Use the Result type for error handling

    master

    The Result<A, B> type is used to represent the outcome of an operation without relying on exceptions. It is a union type consisting of either an Ok<A> (representing success with value of type A) or an Error<B> (representing failure with error of type B).

    This pattern allows you to chain operations using functional primitives like flatMap and handle errors gracefully using match.

    type Result<A, B> = Ok<A> | Error<B>
  8. Run ts-belt benchmarks locally

    master

    To run the benchmark suites for ts-belt, you must first clone the repository, build the library, and then set up the benchmarks directory.

    Steps to run benchmarks:

    1. Clone the repository
    2. Install dependencies and build ts-belt using yarn build dist -t.
    3. Navigate to the benchmarks directory and install its specific dependencies.
    4. Execute the benchmark suite using yarn start to run the tests, or yarn generate to produce a markdown report.

    Results are saved in the benchmarks/.results directory.

    # 1. Clone the repo
    git clone https://github.com/mobily/ts-belt.git
    
    # 2. Install dependencies and build ts-belt
    yarn
    yarn build dist -t
    
    # 3. Setup benchmarks directory
    cd ./benchmarks
    yarn
    
    # 4. Run benchmarks
    yarn start
    # OR generate a markdown file
    yarn generate
  9. Configure TypeScript for ts-belt

    master

    To get the most benefit from ts-belt's type safety, it is highly recommended to enable strict mode and unchecked indexed access in your tsconfig.json. This ensures that the library's functional patterns and type guarantees are correctly enforced by the compiler.

    {
      "compilerOptions": {
        "strict": true,
        "strictNullChecks": true,
        "noUncheckedIndexedAccess": true
      }
    }