one-firework
Version:
A library for singal use function execution.
100 lines (64 loc) β’ 2.66 kB
Markdown
# one-firework π§¨
_Explode once. Never again._
> π‘ A single-execution function utility β type-safe, side-effect-proof, and featherlight.
`one-firework` ensures your function **runs exactly once**, no matter how many times itβs called. Perfect for **initializations**, **expensive computations**, or **preventing repeated side effects**. All with **type safety**, **reset control**, and zero bloat. Control the way your code runs.
## β¨ Features
- β
**One-shot execution** β Your function, but strictly once.
- π **Type-safe & secure** β Written in TypeScript, scanned by Snyk.
- β‘ **Blazingly fast** β Perfect match for Bun.
- πͺΆ **Featherlight** β No overhead, no nonsense.
- π§ **Predictable control flow** β Say goodbye to accidental re-runs.
- π **Resettable** β Need another spark? Just reset.
## π Installation Guide
```sh
β‘bun add one-firework
```
or
```bash
π¦npm install one-firework ~ π Classic launch
πβyarn add one-firework ~ π Smooth glide
```
## π§ Usage
```ts
import firework from 'one-firework'
function expensiveCalculation(a: number, b: number): number {
console.log("Performing expensive calculation...");
return a + b;
}
const onceCalculation = firework(expensiveCalculation);
onceCalculation(5, 3); // π 8
onceCalculation(9, 1); // π 8 (ignored)
onceCalculation(2, 3); // π 8 (still ignored)
firework.fired(onceCalculation); // π 3 (calls tracked)
```
### ~ with options `throwOnMaxCalls`
```ts
const runOnce = firework(expensiveCalculation, { throwOnMaxCalls: true });
runOnce(1, 2); // β
Executes
runOnce(3, 4); // β Throws: function already called
```
## π€ API
### firework(func, options?)
Returns a function that invokes `func` only on the first call.
#### func
Type: `Function` -
The function to protect from repeated execution.
#### options _(Optional)_
Type: `Object`
##### throwOnMaxCalls
- Type: `boolean`,
- Default: `false`
- If `true`, calling more than once throws an error.
### firework.fired(func)
Returns the number of times the function was called.
> βΉοΈ Note: This only works when the function is wrapped with firework.
> β³ _Coming soon_: You'll be able to call .fired directly on the function (fn.fired) without needing to wrap it!
## πWhy one-firework?
Sometimes, you only want the fuse to burn once β like:
- Setting up a singleton
- Subscribing to an event
- Running an initialization block
- Avoiding duplicate requests
Let one-firework handle that β beautifully, safely, and with a little style. π§¨
### License
[MIT](https://choosealicense.com/licenses/mit/)