npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@rimbu/base

v2.0.5

Published

Utilities to implement Rimbu collections

Downloads

16,765

Readme

npm version License Types Included Node Bun ESM + CJS

@rimbu/base

Foundational immutable array and utility primitives powering all other Rimbu collections.

@rimbu/base exposes a small, efficient set of low-level utilities (array operations, tuple helpers, type predicates, error types) used internally across Rimbu’s high-level data structures. While primarily an implementation substrate, you can use these helpers directly for performance‑aware immutable array manipulation and advanced type constraints.

Think: ultra-focused building blocks for persistent & type‑rich collections.

Full documentation: Rimbu Docs · Rimbu API


Table of Contents

  1. Why Rimbu Base?
  2. Feature Highlights
  3. Quick Start
  4. Immutable Array Operations (Arr)
  5. Tuple & Token Utilities
  6. Type Utilities (plain-object)
  7. Error Types (RimbuError)
  8. Installation
  9. FAQ
  10. Contributing
  11. License
  12. Attributions
  13. Quick Reference

Why Rimbu Base?

High‑level persistent collections depend on fast, predictable low‑level primitives. Instead of rewriting array cloning, sparse copying, index‑safe mutation, and structured error handling in every package, @rimbu/base centralizes these operations:

  • Consistency – shared implementations eliminate subtle divergence.
  • Performance – leverages modern Array prototype methods (toSpliced, toReversed, with, at) when available; falls back gracefully.
  • Immutability by default – every operation returns a new array only when changes occur (structural sharing where possible).
  • Sparse array awareness – preserves sparsity for specialized internal block layouts.
  • Type guards & predicates – compile‑time discrimination for plain objects vs. functions/iterables.
  • Focused surface – zero external runtime dependencies (aside from internal Rimbu type modules).

Use it directly if you need ergonomic immutable array helpers without pulling in full collection abstractions.


Feature Highlights

  • Arr Immutable Opsappend, prepend, concat, reverse, update, mod, insert, splice, tail, init, last, mapSparse, copySparse.
  • Conditional Optimization – automatically chooses modern O(1) helpers when your runtime supports them.
  • Tuple HelpersEntry.first, Entry.second for lightweight entry handling in map-like structures.
  • Type PredicatesIsPlainObj, IsArray, IsAny, plus runtime isPlainObj, isIterable.
  • Structured Errors – clear error signaling via custom error classes (e.g. InvalidStateError).
  • Sentinel Token – a shared Token symbol for internal identity and tagging.
  • Tree-shakable – import only what you use: import { Arr } from '@rimbu/base';.

Quick Start

import { Arr } from '@rimbu/base';

const base = [1, 2, 3];

// Pure modification: only clones when the value actually changes
const incremented = Arr.mod(base, 1, (v) => v + 1); // [1, 3, 3]

// Structural no-op returns original reference for efficiency
const same = Arr.mod(base, 5, (v) => v); // index out of range → original

// Append without mutating
const appended = Arr.append(incremented, 4); // [1, 3, 3, 4]

// Reverse slice
const reversed = Arr.reverse(appended); // [4, 3, 3, 1]

console.log(base); // [1, 2, 3]

Immutable Array Operations (Arr)

All functions accept a readonly T[] input and return either the original array (when unchanged) or an optimized clone.

| Function | Purpose | | -------------------- | --------------------------------------------------------- | | append | Add element at end (non-empty array optimization). | | prepend | Add element at start efficiently. | | concat | Smart concat – reuses original when one side empty. | | reverse | Fast reversed copy (range slice optional). | | forEach | Controlled traversal with optional reverse + halt state. | | map / reverseMap | Indexed transformation forward or backward. | | last | O(1) last element access (uses .at(-1) when available). | | update | Apply Update<T> logic at index (no-op preserved). | | mod | Lightweight element modification via (value)=>value'. | | insert | Insert at index. | | tail / init | Drop first / last element. | | splice | Immutable variant of native splice. | | copySparse | Preserve holes in sparse arrays. | | mapSparse | Transform only present indices, keeping sparsity. |

Design details:

  • Uses native copy-on-write style helpers when available for speed.
  • Avoids unnecessary cloning when an update is identity.
  • Preserves array holes for internal block structures requiring sparse layout semantics.

Tuple & Token Utilities

import { Entry, Token } from '@rimbu/base';

const pair: readonly [string, number] = ['age', 42];
Entry.first(pair); // 'age'
Entry.second(pair); // 42

// Shared sentinel for internal tagging / identity
if (someValue === Token) {
  /* special branch */
}

Type Utilities (plain-object)

Compile-time predicates for discriminating plain data objects from complex / functional structures:

| Type | Description | | ----------------- | ---------------------------------------------------------------------------------- | | IsPlainObj<T> | True only for non-iterable, non-function object types without function properties. | | PlainObj<T> | Narrows to T if IsPlainObj<T>; otherwise never. | | IsArray<T> | Resolves to true if T is a (readonly) array type. | | IsAny<T> | Detects any. | | isPlainObj(obj) | Runtime guard for plain data objects. | | isIterable(obj) | Runtime guard for Iterable. |

Use these when building APIs that must reject iterables or functions while retaining strong type discrimination.


Error Types (RimbuError)

Structured error classes provide meaningful failure contexts internally and externally:

| Error Class | Trigger Scenario | | ---------------------------------------- | ---------------------------------------------- | | EmptyCollectionAssumedNonEmptyError | An operation expected a non-empty collection. | | ModifiedBuilderWhileLoopingOverItError | Mutating a builder mid-iteration. | | InvalidStateError | Internal invariant breach (should not happen). | | InvalidUsageError | Consumer used an API incorrectly. |

Helper throw functions exist for concise signaling (throwInvalidStateError(), etc.). Prefer them for consistency.


Installation

Compabitity

Package Managers

Yarn:

yarn add @rimbu/base

npm:

npm install @rimbu/base

Bun:

bun add @rimbu/base

Deno:

deno add npm:@rimbu/base

Usage

import { Arr } from '@rimbu/base';

const arr = [1, 2, 3];
console.log(Arr.mod(arr, 1, (v) => v + 1));
// [1, 3, 3]

console.log(arr);
// [1, 2, 3]

Author

Created and maintained by Arvid Nicolaas.

Contributing

We welcome contributions! Please read our Contributing guide.

Contributors

Made with contributors-img.

License

This project is licensed under the MIT License. See the LICENSE for details.