@offchain/js-utils
v1.0.1
Published
Frequently used tools and utilities
Downloads
8
Readme
@offchain/js-utils
Frequently used JavaScript/TypeScript utilities used across Offchain projects.
These utilities are tree-shakeable, typed, and framework-agnostic. The library currently exposes:
arrayUtils— a static utility class for common array operations (shuffle, unique, safe reductions for numbers/BigNumber/bigint, chunking, etc.).selectValue— a tiny helper to pick a chain-specific value from a map with adefaultfallback (for projects usingviem).
Table of Contents
- Features
- Installation
- Quick Start
- API Reference
- TypeScript
- Build
- Testing
- Project Structure
- Contributing
- License
Features
- Small, typed helpers for arrays and chain-based selection
- ESM and CommonJS builds
- Zero runtime dependencies in this package (uses peer deps where appropriate)
- Full TypeScript definitions
Installation
This package expects certain peer dependencies if you use matching APIs:
bignumber.js— required if you usearrayUtils.safeReducewithBigNumberinputsviem— required if you useselectValue
Install with your favorite package manager:
# with npm
npm install @offchain/js-utils bignumber.js viem
# with pnpm
pnpm add @offchain/js-utils bignumber.js viem
# with yarn
yarn add @offchain/js-utils bignumber.js viemIf you do not use safeReduce (BigNumber variant) or selectValue, you may omit the corresponding peer dependency.
Quick Start
ESM:
import { arrayUtils, selectValue } from "@offchain/js-utils"
import { mainnet, sepolia, base } from "viem/chains"
// array helpers
const shuffled = arrayUtils.shuffle([1, 2, 3, 4])
const unique = arrayUtils.onlyUnique([1, 1, 2, 3]) // [1,2,3]
const chunks = arrayUtils.toChunks([1,2,3,4,5], 2) // [[1,2],[3,4],[5]]
// precise sum using BigNumber under the hood
// (works with number[] and BigNumber[])
import BigNumber from "bignumber.js"
const sum = arrayUtils.safeReduce([0.1, 0.2]) // BigNumber(0.3)
const sumBN = arrayUtils.safeReduce([new BigNumber(1), new BigNumber(2)]) // BigNumber(3)
// selectValue for chain-specific configuration
const rpcUrl = selectValue(base, {
Mainnet: "https://mainnet.example",
Base: "https://base.example",
default: "https://fallback.example"
})CommonJS:
const { arrayUtils, selectValue } = require("@offchain/js-utils")API Reference
arrayUtils
A static utility class with the following methods:
randomElement
randomElement<T>(array: T[]): TReturns a randomly selected element from the array.
shuffle
shuffle<T>(array: T[]): T[]In-place Fisher–Yates shuffle. Returns the same array instance with elements shuffled.
exclude
exclude<T>(source: T[], ...exclusions: T[][]): T[]Returns a new array of items from source that are not present in provided exclusion lists.
onlyUnique
onlyUnique<T>(array: T[]): T[]Returns a new array with duplicates removed while preserving type.
nonNullable
nonNullable<T>(array: T[]): NonNullable<T>[]Filters items by Boolean. Note: filter(Boolean) removes all falsy values, including 0 and "". If you need to keep 0 or empty strings, write a custom predicate.
asyncNonNullable
asyncNonNullable<T>(array: Promise<T[]>): Promise<NonNullable<T>[]>awaits the array and then applies nonNullable.
asyncMap
asyncMap<T, R>(array: Promise<T[]>, predicate: (item: T) => R): Promise<R[]>awaits the array and then maps using the provided predicate.
toChunks
toChunks<T>(array: T[], chunkSize: number): T[][]Splits an array into chunks of size chunkSize. The last chunk may be shorter.
safeReduce
safeReduce(arr: number[] | BigNumber[]): BigNumberSafely sums numbers using BigNumber under the hood to avoid floating‑point errors. Accepts number[] or BigNumber[]. For empty arrays returns BigNumber(0). For single‑element arrays returns that value as BigNumber.
safeReduceInt
safeReduceInt(arr: bigint[]): bigintSums an array of bigint. For empty arrays returns 0n. For single‑element arrays returns that element.
selectValue
selectValue<T = any>(chain: Chain, list: { [key: string]: T } & { default: T }): TSelects a value based on chain.name from viem. If there is no exact match, falls back to list.default.
Example:
import { base, mainnet } from "viem/chains"
import { selectValue } from "@offchain/js-utils"
const rpc = selectValue(base, {
Mainnet: "https://mainnet.example",
Base: "https://base.example",
default: "https://fallback.example"
})TypeScript
- Full type definitions are bundled. The package exports proper
.d.tsfiles via Vite +vite-plugin-dts. - Path aliases (if any) are handled during build; consumers import from the public API only.
Build
- Library build uses Vite library mode.
- Formats: ESM (
.mjs) and CommonJS (.js). - Entry:
src/index.ts.
Run:
npm run buildArtifacts are emitted to dist/.
Testing
The project uses vitest.
- Run the tests:
npm test- Run tests with coverage:
npm run test:coverageCoverage reports are written to the coverage/ directory.
Project Structure
src/
index.ts # Public API (re-exports)
utils/
array-utils.ts # arrayUtils implementation
array-utils.spec.ts # tests
select-value.ts # selectValue helper
select-value.spec.ts # testsContributing
- Issues: https://gitlab.onmau.dev/offchain/js-utils/issues
- Merge requests are welcome. Please include tests when adding/changing functionality.
- Code style: keep consistent with existing files and run tests locally before submitting.
License
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0).
See LICENSE for details.
