iif-ts
Version:
> ๐ง A tiny utility for conditional insertion into arrays and objects using the spread operator. Supports lazy evaluation.
91 lines (62 loc) โข 1.72 kB
Markdown
# iif-ts
> ๐ง A tiny utility for conditional insertion into arrays and objects using the spread operator. Supports lazy evaluation.
## โจ Features
- โ
Drop-in use with `...spread`
- โ
Supports arrays (`iifArray`) and objects (`iifObject`)
- โ
Lazy evaluation with functions
- โ
Zero runtime dependencies
- โ
Fully typed with TypeScript
## ๐พ Installation
```bash
pnpm add iif-ts
# or
npm install iif-ts
# or
yarn add iif-ts
```
## ๐ง Usage
### โค Arrays: iifArray
```ts
import { iifArray } from 'iif-ts'
const arr = [
'a',
...iifArray(true, 'b', 'c'), // ['b', 'c']
]
const lazy = [...iifArray(condition, () => computeHeavyValue())]
```
### โค Objects: iifObject
```ts
import { iifObject } from 'iif-ts'
const obj = {
name: 'Islam',
...iifObject(true, { role: 'admin' }), // adds "role" if true
}
const safe = {
...iifObject(user?.active, () => ({ token: user.token })),
}
```
## ๐ API
```ts
iifArray<T>(condition: boolean, ...values: (T | (() => T))[]): T[]
```
- condition โ If true, the values are included.
- values โ One or more values or lazy functions returning values.
- โ
Returns an array or empty array.
```ts
iifObject<T>(condition: boolean, value: T | (() => T)): Partial<T>
```
- condition โ If true, the object is returned.
- value โ An object or a lazy function returning one.
- โ
Returns an object or {}.
## ๐ Example with JSX (React)
```ts
{...iifObject(isDev, { 'data-dev': true })}
{...iifArray(showTooltip, 'aria-label')}
```
## ๐งช Testing
This package is fully covered by TypeScript type checks. For full runtime tests, add your own test framework like Vitest or Jest.
## ๐ License
Apache-2.0 ยฉ Islam Yamor