A LITTLE UTILITY WITH A LOT OF USES
Small function.
Endless possibilities.
Move to the previous index. Reach the start. Wrap around.
A tiny JavaScript helper for things that go around.
Zero dependencies · CommonJS + ESM · TypeScript ready
01 / THE PLAYGROUND
See the cycle in action.
Change the numbers. Follow the loop.
cyclicPrev(max, curr, dec)0
02 / A FEW GOOD USES
Put your loops to work.
Less index math. More building.
A carousel that never runs out of slides.
03 / THE WHOLE API
Three inputs.
One previous index.
Use a positive safe integer cycle size. Current index and step are safe integers; negative values work too.
Read the full documentation ↗cyclicPrev(max, curr = 0, dec = 1)| Parameter | Default | What it does |
|---|---|---|
max | required | Number of positions in the cycle |
curr | 0 | Your current position |
dec | 1 | How far to move backward |
Returns a normalized integer in [0, max). Invalid bounds throw RangeError; invalid current indexes or steps throw TypeError. Operands are reduced before subtraction to keep safe integer arithmetic accurate. The visual playground limits cycle sizes to 1–24; the library does not.
04 / THE COMPANION
Ready to move forward?
cyclic-next moves to the next index and wraps from the last position to the first.
Try the cyclic-next playground ↻npm install cyclic-next cyclic-prevconst cyclicNext = require('cyclic-next');
const cyclicPrev = require('cyclic-prev');
cyclicNext(5, 4); // 0: forward to the first
cyclicPrev(5, 0); // 4: backward to the lastBoth packages ship CommonJS, ES modules, and TypeScript declarations with zero runtime dependencies. Their edge cases differ: cyclic-next v1 preserves JavaScript remainder behavior; cyclic-prev validates safe integers and normalizes the result into [0, max).
Keep things moving.
A small, MIT-licensed utility. Built to fit right in.
Get cyclic-prev on npm ↗