|
| 1 | +# RotatableArray |
| 2 | + |
| 3 | +A tiny, simple, zero-dependency circular array for TypeScript / JavaScript. I created this to use within my own projects. Nothing fancy, nice and simple. |
| 4 | + |
| 5 | +--- |
| 6 | + |
| 7 | +## Install |
| 8 | + |
| 9 | +```bash |
| 10 | +npm i rotatable-array |
| 11 | +```` |
| 12 | + |
| 13 | +--- |
| 14 | + |
| 15 | +## Quick Start |
| 16 | + |
| 17 | +```ts |
| 18 | +import { RotatableArray } from "rotatable-array"; |
| 19 | +
|
| 20 | +const rot = new RotatableArray(["A", "B", "C"]); |
| 21 | +console.log(rot.next()); // A |
| 22 | +console.log(rot.peek(1)); // C |
| 23 | +console.log(rot.next()); // B |
| 24 | +console.log(rot.previous()); // B |
| 25 | +console.log(rot.move(1)); // C |
| 26 | +``` |
| 27 | +
|
| 28 | +### Iteration |
| 29 | +
|
| 30 | +```ts |
| 31 | +for (const x of rot) // infinite round-robin |
| 32 | + console.log(x); |
| 33 | +
|
| 34 | +for (const x of rot.cycle()) // one full pass then stops |
| 35 | + console.log(x); |
| 36 | +``` |
| 37 | +
|
| 38 | +--- |
| 39 | +
|
| 40 | +## API |
| 41 | +
|
| 42 | +| method | summary | |
| 43 | +| ------------------------------ | ---------------------------- | |
| 44 | +| `next()` | return current, advance | |
| 45 | +| `peek(offset=0)` | inspect without moving | |
| 46 | +| `move(offset)` | jump ±offset | |
| 47 | +| `previous()` | `move(-1)` shortcut | |
| 48 | +| `setIndex(i)` / `resetIndex()` | absolute jumps | |
| 49 | +| `add(...items)` | insert after cursor | |
| 50 | +| `removeAt(i = current)` | delete & return item | |
| 51 | +| `shuffle()` | in-place shuffle, cursor → 0 | |
| 52 | +| `toArray()` | snapshot copy | |
| 53 | +| `length` | live item count | |
| 54 | +| `Symbol.iterator` | infinite iterator | |
| 55 | +| `cycle()` | one-pass generator | |
0 commit comments