fixed-len-array
Version:
A tiny and type-safe TypeScript utility to create and work with fixed-length arrays (tuples).
89 lines (62 loc) โข 2.69 kB
Markdown
A tiny and type-safe TypeScript utility to create and work with **fixed-length
arrays (tuples)**. Automatically trims or pads input arrays at runtime, while
offering compile-time safety using TypeScript's type system.
<div align="center">
<p>
<a href="https://www.npmjs.com/package/fixed-len-array"><img src="https://img.shields.io/npm/v/fixed-len-array.svg" alt="NPM Version"/></a>
<a href="https://github.com/ptprashanttripathi/fixed-len-array/actions"><img src="https://img.shields.io/github/actions/workflow/status/ptprashanttripathi/fixed-len-array/npm-publish.yml?branch=main" alt="Build Status"/></a>
<a href="https://github.com/ptprashanttripathi/fixed-len-array/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/fixed-len-array.svg" alt="MIT License"/></a>
<a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-Ready-blue.svg" alt="TypeScript Ready"/></a>
<a href="https://github.com/ptprashanttripathi/fixed-len-array/blob/main/docs"><img src="https://img.shields.io/badge/docs-available-brightgreen.svg" alt="Documentation"/></a>
</p>
</div>
- โ
Enforces fixed-length array types (tuples)
- ๐ง Type-safe construction
- ๐ง Automatically trims or pads at runtime
- ๐ฆ Tiny, no dependencies
- ๐ Works in both Node.js and browser environments (ESM only)
## ๐ Usage
```sh
npm install fixed-len-array
```
```ts
import { toFixedLengthArray, FixedLengthArray } from "fixed-len-array";
// Pads to a fixed length of 3
const vec3 = toFixedLengthArray([1], 3, 0);
// Result: [1, 0, 0]
// Trims if input is longer
const trimmed = toFixedLengthArray([1, 2, 3, 4, 5], 3, 0);
// Result: [1, 2, 3]
// Full type support
type Vec3 = FixedLengthArray<3, number>;
```
Creates a fixed-length array by trimming or padding the input.
A recursive type that represents a tuple of length `N`, with all elements of
type `T`.
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md)
for details.
```bash
git clone https://github.com/ptprashanttripathi/fixed-len-array.git
cd fixed-len-array
npm install
npm run build
npm test
```
This project is [MIT](LICENSE) licensed.
---
<div align="center">
<p>Made with โค๏ธ by <a href="https://github.com/ptprashanttripathi">Pt. Prashant Tripathi</a></p>
<p>โญ Star this repo if you find it helpful!</p>
</div>