# @mongez/reinforcements — Full reference

> Complete API reference for `@mongez/reinforcements` v4.1. This file is the concatenation of every per-namespace skill, intended for single-fetch loading by AI agents.

Install: `npm i @mongez/reinforcements`, `pnpm add @mongez/reinforcements` or `yarn add @mongez/reinforcements`.

All exports import from the package root:

```ts
import {
  get, set, has, pick, omit, compact, merge, clone, areEqual,
  toCamelCase, slugify, truncate, template,
  clamp, formatBytes, percentage,
  debounce, throttle, memoize, pipe,
  sleep, retry, pMap, pProps, defer,
  Random, lazy,
  type Path, type PathValue, type DeepPartial,
} from "@mongez/reinforcements";
```

---

# Overview

> **Auto-trigger:** code first imports anything from `@mongez/reinforcements` and orientation is needed; user asks "what is @mongez/reinforcements / how do I install it / what does this package do / which @mongez package should I use for X"; package.json adds `"@mongez/reinforcements"` as a dependency.
> **Skip when:** a specific namespace skill (objects, strings, numbers, arrays, async, functions, lazy, random, mixed, types, recipes) already covers the user's concrete task — load that one directly; questions about unrelated `@mongez/*` packages (`@mongez/supportive-is`, `@mongez/collections`) beyond brief scope-boundary mentions.

`@mongez/reinforcements` is a TypeScript utility belt — ~130 functions for objects, strings, numbers, async, randomness, and functional composition.

## Install

```sh
yarn add @mongez/reinforcements
# or
npm i @mongez/reinforcements
```

## Import pattern

Everything is exported from the package root:

```ts
import {
  get, set, has, pick, omit, merge, clone, areEqual,
  toCamelCase, slugify, truncate, template,
  clamp, formatBytes, percentage,
  debounce, throttle, memoize, pipe,
  sleep, retry, pMap, defer,
  Random, lazy,
  type Path, type PathValue, type DeepPartial,
} from "@mongez/reinforcements";
```

## Namespaces

| Namespace | Count | Examples |
|---|---|---|
| `object` | 24 | `get`, `set`, `pick`, `omit`, `merge`, `clone`, `flatten`, `walk`, `diff`, `when` |
| `string` | ~45 | Casing family, `slugify`, `truncate`, `template`, `mask`, `stripHtmlTags` |
| `number` | 14 | `round`, `clamp`, `formatBytes`, `formatDuration`, `ordinal`, `percentage`, `safeDivide` |
| `mixed` | 4 | `clone`, `areEqual`, `shuffle`, `coalesce` |
| `array` | 25 | `chunk`, `range`, `unique`, `pluck`, `groupBy`, `partition`, `keyBy`, `union`, `zip`, `sum` |
| `random` | 14 | `Random.int`, `Random.uuid`, `Random.sample`, `Random.seed` |
| `lazy` | 1 + variants | `lazy`, `lazy.async`, `lazy.from`, `isLazy` |
| `function` | 18 | `debounce`, `throttle`, `memoize`, `pipe`, `curry`, `once`, `attempt` |
| `async` | 14 | `sleep`, `retry`, `retryable`, `timeout`, `pMap`, `pFilter`, `pReduce`, `poll`, `waitFor`, `defer` |
| `types` | 16 | `Path`, `PathValue`, `DeepPartial`, `Branded`, `Prettify` |

## Scope boundaries

| Concern | Lives in | Why |
|---|---|---|
| Type/shape predicates (`isString`, `isEmpty`, `isURL`, …) | `@mongez/supportive-is` | Single-purpose package |
| Chainable collection API + heavy ops (`sortBy`, `where`, `flatMap`, …) | `@mongez/collection` | Richer collection model |
| HTML sanitization | Use `DOMPurify` | Parser-based, not regex |
| Schema validation | Use `zod` / `valibot` | Out of scope |
| Date manipulation | Use `dayjs` / `date-fns` / `Temporal` | Out of scope |
| HTTP/fetch helpers | Separate concern | Out of scope |

## Mental model

- **Object utilities** prefer **paths over keys** — dot-notation is first-class.
- **String casings** are powered by a shared `words()` tokenizer that handles acronyms correctly (`AIAgent` → `["AI", "Agent"]`).
- **Async helpers** mirror common needs without re-implementing the whole Bluebird/p-* ecosystem.
- **`Random`** is a namespace class — `Random.int(1, 10)`, never `new Random()`.
- **`lazy`** is the unique tool for breaking ES-module circular imports.

## TypeScript

`get(obj, path)` autocompletes every legal dot-notation path on `obj` and infers the value type. Generics flow through `pick`, `omit`, `merge`, `clone`, `keys`, `values`, `entries`, `mapValues`, `pipe`, `compose`, and the async helpers.

```ts
type User = { profile: { email: string } };
const u: User = { profile: { email: "x@y.z" } };

get(u, "profile.email"); // typed as string
```

---

# Objects

> **Auto-trigger:** code imports `get`, `set`, `has`, `unset`, `pick`, `omit`, `compact`, `merge`, `clone`, `flatten`, `freeze`, `defaults`, `invert`, `mapValues`, `mapKeys`, `map`, `keys`, `values`, `entries`, `fromEntries`, `walk`, `diff`, or `sort` from `@mongez/reinforcements`; user asks "how do I read/write a deep path / dot-notation get / pick keys / omit keys / deep merge / flatten an object / diff two objects"; `import { get, set, pick, omit, merge, clone } from "@mongez/reinforcements"`.
> **Skip when:** @mongez/supportive-is is type predicates (`isPlainObject`, `isEmpty`) — use it to test shape, not transform; @mongez/collections handles array-of-object operations (`sortBy`, `keyBy`, `partition`); native `Object.assign`/spread when nesting isn't involved.

Path-aware reads/writes, deep transforms, structural diff. Import from `@mongez/reinforcements`.

## Path access — `get` / `set` / `has` / `unset`

#### `get`

```ts
get<T, P extends Path<T>>(obj: T, path: P, default?): PathValue<T, P>
get<T = any>(obj: any, path: string, default?: T): T
```

Read by typed dot-notation. Falsy values pass through correctly (no spurious default-substitution on `0` / `""` / `false`).

```ts
get({ user: { email: "ada@x.com" } }, "user.email"); // "ada@x.com"
get({ user: {} }, "user.email", "n/a"); // "n/a"
get(arr, "0.name"); // numeric segments index arrays
```

#### `set`

```ts
set<T>(obj: T, path: string, value: unknown): T
```

Mutating write by dot-notation. **Auto-creates arrays** when the next segment is a numeric index of at most 10,000.

```ts
set({}, "users.0.name", "Ada"); // { users: [{ name: "Ada" }] }
set(obj, "a.b.c", 1);            // creates a.b.c chain
```

**Prototype-pollution guard.** A path with a segment of `__proto__`, `constructor`, or `prototype` is rejected — the object is returned untouched. Only OWN members are descended into: an inherited name such as `toString` or `push` is treated as missing (an own container shadows it), so a path can never reach `Object.prototype`, `Array.prototype` or a built-in function. A path that would descend into an existing primitive or function (`set({ a: 1 }, "a.b", 2)`) also returns the object untouched instead of throwing. Matters whenever `path` comes from untrusted input (e.g. a JSON body walked into `set`).

**Array-index bound.** A newly created container is an array only when the next numeric segment is at most 10,000; a larger index (`set({}, "a.4294967294", "x")`) creates a plain object `{ a: { "4294967294": "x" } }`, so an untrusted path cannot build a huge sparse array. Existing arrays are written as they are, whatever the index.

```ts
set({}, "__proto__.polluted", 1); // {} — rejected, no throw
```

#### `has`

```ts
has(obj: any, path: string): boolean
```

`true` if the path exists, **even when the value is `undefined`**. Use this to distinguish "missing" from "present-but-undefined".

```ts
has({ a: { b: 1 } }, "a.b");         // true
has({ a: { b: undefined } }, "a.b"); // true
has({ a: {} }, "a.b");               // false
```

#### `unset`

```ts
unset<T>(obj: T, paths: readonly string[]): T
```

Mutating remove by dot-notation. Returns the same reference.

```ts
unset({ a: 1, b: 2 }, ["a"]);          // { b: 2 }
unset({ a: { b: 1, c: 2 } }, ["a.b"]); // { a: { c: 2 } }
```

## Key selection — `pick` / `omit`

#### `pick`

```ts
pick<T, K extends keyof T>(obj: T, keys: readonly K[]): Pick<T, K>
pick(obj, keys: string[]): Record<string, any>     // supports dot-notation paths
pick(obj, predicate: (value, key) => boolean): Record<string, any>
```

```ts
pick({ a: 1, b: 2, c: 3 }, ["a", "c"]);         // { a: 1, c: 3 }
pick({ a: { b: 1, c: 2 } }, ["a.b"]);           // { a: { b: 1 } }
pick({ a: 1, b: 2, c: 3 }, v => v > 1);         // { b: 2, c: 3 }
```

#### `omit`

```ts
omit<T, K extends keyof T>(obj: T, keys: readonly K[]): Omit<T, K>
omit(obj, keys: string[]): Record<string, any>     // supports dot-notation paths
omit(obj, predicate: (value, key) => boolean): Record<string, any>
```

Non-mutating; returns a shallow clone minus the keys/paths.

```ts
omit({ a: 1, b: 2 }, ["b"]);                    // { a: 1 }
omit({ a: { b: 1, c: 2 } }, ["a.b"]);           // { a: { c: 2 } }
omit({ a: 1, b: 2 }, (_, k) => k === "a");      // { b: 2 }
```

> `only` and `except` are kept as **`@deprecated` aliases** of `pick` and `omit` — prefer the new names.

> `pick` and `omit` walk dot-notation paths through `set`/`get` internally and inherit the `__proto__`/`constructor`/`prototype` guard — a malicious path can't be used to read or reconstruct a polluted prototype.

## Cleanup — `compact`

#### `compact`

```ts
compact<T extends Record<string, any>>(obj: T, options?: CompactOptions): Partial<T>
compact<T>(array: T[], options?: CompactOptions): T[]

type CompactOptions = {
  predicate?: (value: any) => boolean;  // default: nullish or ""
  empties?: boolean;                    // default: true — drop [] and {} too
  deep?: boolean;                       // default: true
};
```

Strip "empty" entries from objects/arrays. Default predicate drops `null`, `undefined`, and `""` only — **keeps `0`, `false`, `NaN`** because those are usually meaningful. With `empties` and `deep` on by default, parent containers that become empty after recursion are themselves dropped.

```ts
compact({ name: "Ada", email: "", phone: null, age: 0 });
// { name: "Ada", age: 0 }

compact({ user: { name: "Ada", email: "" }, meta: {} });
// { user: { name: "Ada" } }

compact(["a", "", null, "b"]);
// ["a", "b"]

compact({ a: 0, b: -1 }, { predicate: v => v === -1 });
// { a: 0 }

compact({ tags: [], name: "Ada" }, { empties: false });
// { tags: [], name: "Ada" }
```

Typical uses: cleaning API request payloads, building query strings from filter objects, sanitizing form data.

## Conditional construction — `when`

#### `when`

```ts
when<T extends object>(condition: unknown, value: T | (() => T)): Partial<T>
```

Return `value` when `condition` is truthy, otherwise `{}`. Built for **inline conditional spreading** — a key is only present when the condition holds. The value may be a **factory function**, invoked lazily and only when the condition is truthy, so the cost of building it is skipped otherwise.

```ts
const payload = {
  name: "Ada",
  ...when(isAdmin, { role: "admin" }),
};
// isAdmin === true  -> { name: "Ada", role: "admin" }
// isAdmin === false -> { name: "Ada" }

// Lazy value — buildHeavyConfig() runs only when `ready` is truthy.
when(ready, () => ({ config: buildHeavyConfig() }));
```

Cleaner than `...(condition && { … })` (which can spread `false`) and reads as intent at the call site.

## Deep transforms — `merge` / `clone` / `flatten` / `freeze`

#### `merge`

```ts
merge<A, B>(a: A, b: B): A & B
merge(...sources, options?: { arrays?: "replace" | "concat" | "union" }): any
```

Recursive merge of plain objects. Arrays default to **replace**; pass an options object as the last argument to change strategy.

```ts
merge({ a: { b: 1 } }, { a: { c: 2 } });
// { a: { b: 1, c: 2 } }

merge({ list: [1, 2] }, { list: [3, 4] }, { arrays: "concat" });
// { list: [1, 2, 3, 4] }

merge({ list: [1, 2] }, { list: [2, 3] }, { arrays: "union" });
// { list: [1, 2, 3] }
```

**Sub-objects are shared by reference.** The result is a new top-level object, but objects that exist in only one input (or when only one source is given) are the same references as in that input; only keys where both sides are plain objects get a new object, and arrays are copied. Mutating a nested value of the result mutates the input, so `clone()` the result first:

```ts
const a = { shared: { x: 1 } };
const r = merge(a, { other: 1 });
r.shared === a.shared;                  // true
clone(merge(a, { other: 1 })).shared === a.shared; // false
```

Class instances are taken from the latest source rather than merged (cloning custom constructors is out of scope).

**Prototype-pollution guard.** Source keys named `__proto__`, `constructor`, or `prototype` are silently skipped (not merged) at every recursion depth — merging untrusted JSON can never reach `Object.prototype`.

```ts
merge({}, JSON.parse('{"__proto__":{"polluted":1}}')); // {} — key skipped
```

#### `clone`

```ts
clone<T>(value: T): T
```

Deep clone. Handles `Date`, `RegExp`, `Error` (with own props), `Map`, `Set`, typed arrays and `DataView` (only the viewed bytes are copied), `ArrayBuffer`, and **circular references** via internal `WeakMap`. Non-plain class instances are returned by reference.

```ts
const copy = clone({ user: { name: "Ada" }, tags: ["x"] });
copy.user.name = "Bob";
// original is untouched
```

#### `flatten`

```ts
flatten(obj: any, options?: {
  separator?: string;       // default "."
  keepNested?: boolean;     // default false
  maxDepth?: number;        // default Infinity
}): Record<string, any>
```

Flatten to a single-level map of dot-keyed paths. Descends into plain objects, arrays, and class instances. Treats `Date` / `RegExp` / `Map` / `Set` / typed arrays as leaves.

```ts
flatten({ a: { b: 1, c: [2, 3] } });
// { "a.b": 1, "a.c.0": 2, "a.c.1": 3 }

flatten({ a: { b: 1 } }, { separator: "/" });
// { "a/b": 1 }
```

#### `freeze`

```ts
freeze<T>(value: T): Readonly<T>
```

Recursive `Object.freeze` across plain objects and arrays.

```ts
const config = freeze({ api: { url: "..." } });
config.api.url = "x"; // throws in strict mode
```

## Defaults & inversion

#### `defaults`

```ts
defaults<T>(target: T, ...sources): T
```

Mutating: fills only **`undefined`** keys on `target` from each source, left to right.

```ts
defaults({ a: 1 }, { a: 2, b: 3 });   // { a: 1, b: 3 }
defaults({}, { a: 1 }, { a: 2 });     // { a: 1 }  (first source wins)
```

Same prototype-pollution guard as `merge`: `__proto__` / `constructor` / `prototype` keys on any source are skipped.

#### `invert`

```ts
invert<K, V>(obj: Record<K, V>): Record<string, K>
```

Swap keys and values; values are coerced to strings; duplicate values collide last-wins.

```ts
invert({ a: 1, b: 2 }); // { "1": "a", "2": "b" }
```

## Per-entry mapping

#### `mapValues` / `mapKeys`

```ts
mapValues<T, U>(obj: T, fn: (value, key, obj) => U): Record<keyof T & string, U>
mapKeys<T>(obj: T, fn: (key, value, obj) => string): Record<string, T[keyof T]>
```

```ts
mapValues({ a: 1, b: 2 }, v => v * 2);              // { a: 2, b: 4 }
mapKeys({ a: 1, b: 2 }, k => k.toUpperCase());      // { A: 1, B: 2 }
```

#### `map`

```ts
map<T, U>(obj: T, fn: (key, value, obj) => U): U[]
```

Map an object to an array.

```ts
map({ a: 1, b: 2 }, (k, v) => `${k}=${v}`); // ["a=1", "b=2"]
```

## Typed enumeration

```ts
keys<T>(obj: T): Array<keyof T & string>
values<T>(obj: T): Array<T[keyof T]>
entries<T>(obj: T): Array<[keyof T & string, T[keyof T]]>
fromEntries<K, V>(entries: Iterable<readonly [K, V]>): Record<K, V>
```

Typed wrappers around the matching `Object.*` static methods.

## Traversal & comparison

#### `walk`

```ts
walk(obj: any, visitor: (value, path, parent, key) => void, parentPath?: string): void
```

Recursive **leaf** traversal. Descends into plain objects and arrays; calls `visitor` for every non-container value with the full dot-path.

```ts
walk({ a: { b: 1, c: [2, 3] } }, (value, path) => log(path, value));
// "a.b" 1
// "a.c.0" 2
// "a.c.1" 3
```

#### `diff`

```ts
diff(a: object, b: object): {
  added: Record<string, any>;
  removed: Record<string, any>;
  changed: Record<string, { from: any; to: any }>;
}
```

Shallow structural diff; uses deep value equality (`areEqual`) for nested comparison.

```ts
diff({ a: 1, b: 2 }, { a: 1, b: 3, c: 4 });
// { added: { c: 4 }, removed: {}, changed: { b: { from: 2, to: 3 } } }
```

## Sorting

#### `sort`

```ts
sort<T>(obj: T, recursive?: boolean): T  // default recursive = true
```

Return a new object with keys sorted alphabetically. Arrays of objects are out of scope — use `@mongez/collection` `sortBy`.

```ts
sort({ b: 1, a: 2, c: 3 });             // { a: 2, b: 1, c: 3 }
sort({ b: { y: 1, x: 2 }, a: 1 });      // recursive by default
```

## Hostile and very deep input

- **Own `__proto__` keys.** `JSON.parse` produces `"__proto__"` as an ordinary own key. `sort`, `compact`, `mapValues`, `mapKeys`, `pick`/`omit` (predicate form), `clone`, `flatten`, `diff`, `invert`, `keyBy`/`countBy` and `groupBy` write result keys with a define-property helper, so it stays an own key of the result (like `{ ...obj }`) and never swaps the result's prototype.
- **Nesting limit.** `clone`, `merge`, `compact`, `flatten`, `sort`, `walk`, `freeze`, `diff` and `areEqual` accept up to 256 levels of nested objects/arrays and throw a `NestingError` past that (a `RangeError` subclass, message `"<helper>: input is nested deeper than 256 levels"`) instead of overflowing the call stack. The class is not exported: catch it with `error instanceof RangeError` or `error.name === "NestingError"`. `flatten`'s `maxDepth` keeps its meaning (a smaller `maxDepth` stops earlier).
- **Cycles.** `flatten`, `compact`, `sort` and `walk` throw a `NestingError` (`"<helper>: circular reference detected"`) on circular input; shared (non-circular) references are fine. `clone` and `areEqual` keep supporting cycles; `freeze` skips objects it already visited.
- `diff` compares keys by own-property check, so inherited names (`toString`, ...) are no longer treated as present.

---

# Strings

> **Auto-trigger:** code imports `words`, `toCamelCase`, `toStudlyCase`, `toPascalCase`, `toSnakeCase`, `toKebabCase`, `toConstantCase`, `toDotCase`, `toPathCase`, `toTitleCase`, `ucfirst`, `capitalize`, `trim`, `ltrim`, `rtrim`, `replaceAll`, `replaceFirst`, `replaceLast`, `removeFirst`, `removeLast`, `repeatsOf`, `pad`, `padStart`, `padEnd`, `slugify`, `truncate`, `readMoreChars`, `readMoreWords`, `escapeHtml`, `unescapeHtml`, `stripHtmlTags`, `mask`, `template`, `wordCount`, `charCount`, `reverse`, `initials`, `extension`, `toInputName`, `startsWithArabic`, `containsArabic`, `ARABIC_REGEX`, or `ARABIC_PATTERN` from `@mongez/reinforcements`; user asks "how do I camelCase / snake_case / slugify / truncate / mask / strip HTML / get file extension / template with dot-notation / detect Arabic"; `import { toCamelCase, slugify, truncate, mask, template } from "@mongez/reinforcements"`.
> **Skip when:** @mongez/supportive-is is type predicates (`isString`, `isEmail`, `isURL`) — use that for validation, not transformation; HTML sanitization for untrusted input (use `DOMPurify`); i18n translation/pluralization (use `i18next`, `intl-messageformat`); regex escaping uses `escapeRegex` from @mongez/reinforcements-functions, not this skill.

Casing, trimming, replacement, padding, slugify, truncate, mask, template, HTML helpers, Arabic detection. Import from `@mongez/reinforcements`.

## Casing — powered by `words()`

All casing functions share a single tokenizer that handles **acronyms correctly**.

#### `words`

```ts
words(input: string): string[]
```

```ts
words("XMLHttpRequest");  // ["XML", "Http", "Request"]
words("AIAgent");         // ["AI", "Agent"]
words("hello-world");     // ["hello", "world"]
// linear time: a 50 kB run of capitals is safe (all casing helpers build on words)
```

#### Casing family

| Function | Signature | Example |
|---|---|---|
| `toCamelCase` | `(str) => string` | `toCamelCase("XMLHttpRequest")` → `"xmlHttpRequest"` |
| `toStudlyCase` | `(str) => string` | `toStudlyCase("hello-world")` → `"HelloWorld"` |
| `toPascalCase` | `(str) => string` | Alias of `toStudlyCase` |
| `toSnakeCase` | `(str, separator?, lowerAll?) => string` | `toSnakeCase("AIAgent")` → `"ai_agent"` |
| `toKebabCase` | `(str, lowerAll?) => string` | `toKebabCase("getUserID")` → `"get-user-id"` |
| `toConstantCase` | `(str) => string` | `toConstantCase("apiBaseUrl")` → `"API_BASE_URL"` |
| `toDotCase` | `(str, lowerAll?) => string` | `toDotCase("helloWorld")` → `"hello.world"` |
| `toPathCase` | `(str, lowerAll?) => string` | `toPathCase("helloWorld")` → `"hello/world"` |
| `toTitleCase` | `(str, options?: { stopWords? }) => string` | `toTitleCase("the lord of rings")` → `"The Lord of Rings"` |

## Letter case primitives

```ts
ucfirst(str: string): string                 // uppercase first char
capitalize(str: string): string              // ucfirst on every whitespace-separated word
```

```ts
ucfirst("hello");          // "Hello"
capitalize("hello world"); // "Hello World"
```

## Trimming

| Function | Signature | Notes |
|---|---|---|
| `trim` | `(str, needle?: string) => string` | Trims both ends (default: all whitespace, like `String#trim`) |
| `ltrim` | `(str, needle?: string) => string` | Start only (default needle `" "`: spaces only) |
| `rtrim` | `(str, needle?: string) => string` | End only (default needle `" "`: spaces only) |

```ts
trim("  hi  ");          // "hi"
trim("---hi---", "-");   // "hi"
ltrim("//path", "/");    // "path"
rtrim("file.tmp", ".tmp"); // "file"
trim("ababXab", "ab");   // "X" — the whole needle is repeated
trim("abc", "");         // "abc" — empty needle is a no-op
```

All three run in linear time with no regular expressions (index scans; `trim` with the default needle uses native `String#trim`), so a long run of spaces inside a 50 kB string cannot cause ReDoS. `needle` is matched literally, and a multi-character needle is removed whole (`ltrim("abab-x", "ab")` → `"-x"`, `ltrim("abbbb-x", "ab")` → `"bbb-x"`).

## Replacement family

```ts
replaceAll(str, search, replacement): string
replaceFirst(str, search, replacement): string
replaceLast(str, search, replacement): string
removeFirst(str, needle): string     // = replaceFirst(str, needle, "")
removeLast(str, needle): string      // = replaceLast(str, needle, "")
```

`search`/`needle` and `replacement` are literal in all of them: `$&`, `$1`, `` $` `` and `$'` in `replacement` are not expanded, and `replaceFirst`/`removeFirst` match needles containing regex characters (`replaceFirst("a.b.c", ".", "-")` → `"a-b.c"`).

`replaceAll` regex-escapes `search` internally; the others use `indexOf` / `lastIndexOf`.

```ts
replaceAll("a-b-c", "-", "_");        // "a_b_c"
replaceFirst("foo foo foo", "foo", "bar"); // "bar foo foo"
replaceLast("foo bar foo", "foo", "baz");  // "foo bar baz"
```

#### `repeatsOf`

```ts
repeatsOf(str: string, needle: string, caseSensitive?: boolean): number  // default true
```

```ts
repeatsOf("abcabc", "a");       // 2
repeatsOf("AbcAbc", "a", false); // 2
```

`needle` is matched literally — internally escaped before being compiled into a `RegExp`, so regex metacharacters (`.`, `*`, `(`, `|`, …) in `needle` carry no special meaning and a long adversarial `needle` can't trigger catastrophic backtracking (ReDoS).

## Padding

```ts
pad(str, length, char?): string         // pad both sides; extra char goes to end
padStart(str, length, char?): string    // typed wrapper around String#padStart
padEnd(str, length, char?): string      // typed wrapper around String#padEnd
```

```ts
pad("hi", 6);       // "  hi  "
pad("hi", 7, "*");  // "**hi***"
padStart("7", 3, "0"); // "007"
padEnd("7", 3, "0");   // "700"
```

## URL slugs & truncation

#### `slugify`

```ts
slugify(str, options?: {
  separator?: string;  // default "-"
  lower?: boolean;     // default true
  strict?: boolean;    // default true — strip non-alphanumeric per token
}): string
```

```ts
slugify("Hello, World!");                  // "hello-world"
slugify("café crème");                     // "cafe-creme"
slugify("Hello World", { separator: "_" }); // "hello_world"
```

#### `truncate`

```ts
truncate(str, length, options?: {
  suffix?: string;                  // default "..."
  byWord?: boolean;                 // default false — cut at word boundary
  position?: "end" | "middle";      // default "end"
}): string
```

```ts
truncate("hello world", 8);                          // "hello..."
truncate("hello world there", 14, { byWord: true }); // "hello world..."
truncate("abcdefghij", 7, { position: "middle" });   // "ab...ij"
```

#### `readMoreChars` / `readMoreWords`

```ts
readMoreChars(str, length, suffix?: string): string  // default suffix "..."
readMoreWords(str, wordCount, suffix?: string): string
```

```ts
readMoreChars("hello world", 5);     // "hello..."
readMoreWords("a b c d e", 3);       // "a b c..."
```

## HTML & masking

#### `escapeHtml` / `unescapeHtml`

```ts
escapeHtml(str: string): string   // & < > " ' → entities
unescapeHtml(str: string): string // reverse
```

```ts
escapeHtml('<a href="x">');  // "&lt;a href=&quot;x&quot;&gt;"
```

#### `stripHtmlTags`

```ts
stripHtmlTags(str, options?: {
  replacement?: string;              // default ""
  stripScriptsAndStyles?: boolean;   // default true — drops content too
  stripComments?: boolean;           // default true
}): string
```

**Not a sanitizer** — for untrusted HTML, use DOMPurify. Linear time: unterminated tags, `<script` / `<style` openers and `<!--` comments without their closer are left as text instead of being rescanned from every position (no ReDoS on 50 kB of `"<a"` or `"<script"`). Matches are the same as before (a tag runs from `<` + letter to the first `>`). `replacement` is used literally (`$&` is not expanded).

```ts
stripHtmlTags("<p>Hello <b>world</b></p>");        // "Hello world"
stripHtmlTags("<script>alert(1)</script>safe");    // "safe"
stripHtmlTags("<p>hi</p>", { replacement: " " });  // " hi "
```

#### `mask`

```ts
mask(str, options?: {
  start?: number;  // visible chars from start, default 0
  end?: number;    // visible chars from end, default 0
  char?: string;   // mask char, default "*"
}): string
```

```ts
mask("4242424242424242", { start: 0, end: 4 });  // "************4242"
mask("hassan@gmail.com", { start: 2, end: 4 }); // "ha**********.com"
```

## Templates

#### `template`

```ts
template(str: string, vars: Record<string, any>): string
```

`{path}` interpolation with **dot-notation paths** into `vars`. Missing paths render as `""`.

```ts
template("Hello {user.name}!", { user: { name: "Ada" } });
// "Hello Ada!"

template("{count} items", { count: 3 });
// "3 items"
```

## Counting & reversal

```ts
wordCount(str: string): number
charCount(str: string, options?: { unicode?: boolean }): number  // grapheme-aware when true
reverse(str: string): string  // unicode-safe (handles surrogate pairs)
```

```ts
wordCount("hello world");          // 2
charCount("hello");                // 5
charCount("👨‍👩", { unicode: true }); // 1 (single grapheme)
reverse("hello");                  // "olleh"
```

## Misc

#### `initials`

```ts
initials(name: string, separator?: string): string  // default separator ""
```

```ts
initials("Ada Lovelace");      // "AL"
initials("Ada Lovelace", "."); // "A.L"
```

#### `extension`

```ts
extension(filename: string): string
```

Returns the part after the last dot, or `""` if absent.

```ts
extension("foo.txt");          // "txt"
extension("archive.tar.gz");   // "gz"
extension("README");           // ""
```

#### `toInputName`

```ts
toInputName(path: string): string
```

`"a.b.c"` → `"a[b][c]"` for HTML form `name` attributes.

```ts
toInputName("user.address.city"); // "user[address][city]"
toInputName("user.tags[]");        // "user[tags][]"
```

## Arabic

```ts
startsWithArabic(str: string, trimmed?: boolean): boolean  // default trimmed = true
containsArabic(str: string): boolean
ARABIC_REGEX: RegExp                                       // /[؀-ۿ]/
ARABIC_PATTERN: RegExp                                     // @deprecated — same as ARABIC_REGEX
```

```ts
startsWithArabic("مرحبا");        // true
startsWithArabic("   مرحبا");     // true (trimmed)
containsArabic("hello مرحبا");    // true
```

---

# Numbers

> **Auto-trigger:** code imports `round`, `floor`, `ceil`, `toFixed`, `clamp`, `inRange`, `lerp`, `safeDivide`, `percentage`, `parseNumber`, `formatBytes`, or `formatNumber` from `@mongez/reinforcements`; user asks "how do I clamp a number / format bytes / safely divide by zero / round with precision / format currency"; `import { clamp, round, formatBytes, percentage } from "@mongez/reinforcements"`.
> **Skip when:** @mongez/supportive-is handles `isNumber`/`isInteger` predicates — use that for type checks, not arithmetic; date/time math (use `dayjs`, `date-fns`, or `Temporal`); BigInt arithmetic (out of scope).

Rounding, clamping, formatting, safe arithmetic. Import from `@mongez/reinforcements`.

## Rounding with precision

```ts
round(value: number, precision?: number): number  // default 2; rounds half-up
floor(value: number, precision?: number): number  // default 0
ceil(value: number, precision?: number): number   // default 0
toFixed(value: number, precision?: number): number  // returns number, not string
```

```ts
round(1.235, 2);   // 1.24
round(1.5, 0);     // 2     (true rounding, not floor)
floor(1.99, 1);    // 1.9
ceil(1.01, 1);     // 1.1
toFixed(1.236, 2); // 1.24  (number, not "1.24")
```

## Range helpers

```ts
clamp(value: number, min: number, max: number): number
inRange(value: number, min: number, max: number, options?: { inclusive?: boolean }): boolean
lerp(a: number, b: number, t: number): number
```

`clamp` normalizes swapped bounds. `inRange` defaults to `inclusive: true`.

```ts
clamp(15, 0, 10);                          // 10
clamp(-3, 0, 10);                          // 0
inRange(5, 0, 10);                         // true
inRange(10, 0, 10, { inclusive: false });  // false
lerp(0, 100, 0.25);                        // 25
```

## Safe arithmetic

#### `safeDivide`

```ts
safeDivide<F = number>(a: number, b: number, fallback?: F): number | F
```

Returns `fallback` (default `0`) when `b === 0` or the result isn't finite.

```ts
safeDivide(10, 2);          // 5
safeDivide(10, 0);          // 0
safeDivide(10, 0, null);    // null
```

#### `percentage`

```ts
percentage(value: number, total: number, decimals?: number): number  // default 2
```

```ts
percentage(25, 200);   // 12.5
percentage(7, 9, 1);   // 77.8
percentage(1, 0);      // 0   (safe on divide-by-zero)
```

#### `parseNumber`

```ts
parseNumber<F = number>(value: unknown, fallback?: F): number | F
```

Returns `fallback` (default `0`) for `null` / `undefined` / `""` / non-numeric input.

```ts
parseNumber("42");        // 42
parseNumber("abc", -1);   // -1
parseNumber(null, 0);     // 0
```

## Formatting

#### `formatBytes`

```ts
formatBytes(bytes: number, options?: {
  decimals?: number;   // default 2
  binary?: boolean;    // default false (use 1000-based units)
}): string
```

```ts
formatBytes(1500);                          // "1.50 KB"
formatBytes(1024, { binary: true, decimals: 0 }); // "1 KiB"
formatBytes(-1500, { decimals: 0 });        // "-2 KB"
formatBytes(0);                             // "0 B"
```

#### `formatNumber`

```ts
formatNumber(value: number, options?: Intl.NumberFormatOptions & {
  locale?: string | string[];
}): string
```

Thin wrapper around `Intl.NumberFormat`.

```ts
formatNumber(1234.5);                                     // "1,234.5"
formatNumber(0.42, { style: "percent" });                 // "42%"
formatNumber(99, { style: "currency", currency: "USD" }); // "$99.00"
formatNumber(1234, { locale: "ar-EG" });                  // "١٬٢٣٤"
```

#### `formatDuration`

```ts
formatDuration(ms: number, options?: {
  units?: number;      // max unit parts, largest-first; default Infinity
  long?: boolean;      // "1 hour 2 minutes" vs "1h 2m"; default false
  separator?: string;  // default " "
}): string
```

Human-readable duration from milliseconds (days → ms). Shows every non-zero unit by default; cap with `units`.

```ts
formatDuration(3661000);                // "1h 1m 1s"
formatDuration(3661000, { units: 2 });  // "1h 1m"
formatDuration(90000, { long: true });  // "1 minute 30 seconds"
```

#### `ordinal`

```ts
ordinal(value: number, options?: { withNumber?: boolean }): string  // withNumber default true
```

English ordinal for an integer; handles the 11–13 exception and negatives. The fraction is truncated.

```ts
ordinal(1);   // "1st"
ordinal(22);  // "22nd"
ordinal(113); // "113th"
ordinal(2, { withNumber: false }); // "nd"
```

---

# Mixed (clone, areEqual, shuffle, coalesce)

> **Auto-trigger:** code imports `clone`, `areEqual`, `shuffle`, or `coalesce` from `@mongez/reinforcements`; user asks "how do I deep clone / deep compare / shuffle an array / get the first non-null value"; `import { clone, areEqual, shuffle, coalesce } from "@mongez/reinforcements"`.
> **Skip when:** @mongez/supportive-is is type predicates (`isEmpty`, `isPlainObject`) — use that for shape/type checks, not value equality; native `structuredClone` for environments where it suffices and circular custom-class handling isn't required; nullish-coalescing `??` operator when only one fallback is needed.

Deep clone, deep equality, shuffle, coalesce. Import from `@mongez/reinforcements`.

## `clone` — deep copy

```ts
clone<T>(value: T): T
```

Handles `Date`, `RegExp`, `Error` (with own props), `Map`, `Set`, typed arrays and `DataView` (only the viewed bytes are copied, not the whole underlying buffer), `ArrayBuffer`, and **circular references** via internal `WeakMap`. Non-plain class instances are **returned by reference** (cloning user constructors is out of scope — call your own `.clone()` if you have one).

```ts
const a: any = { name: "Ada" };
a.self = a;            // circular
const copy = clone(a);
copy.self === copy;    // true — circular ref preserved

clone(new Date(0));    // new Date instance, same time
clone(/abc/gi);        // new RegExp, same source/flags
clone(new Map([["k", 1]])); // new Map, deep-cloned values

const err = new TypeError("nope");
(err as any).meta = { detail: true };
clone(err).meta;       // { detail: true } — own props preserved
```

## `areEqual` — deep value equality

```ts
areEqual(a: any, b: any): boolean
```

Non-mutating deep equality. **Respects element order in arrays.** Handles `Date`, `RegExp`, `Map`, `Set`, and circular references.

**Depth limit.** `clone` and `areEqual` throw a `NestingError` (`RangeError` subclass, `error.name === "NestingError"`; the class itself is not exported) for data nested deeper than 256 levels instead of overflowing the call stack. Cycles and shared references are still supported. An own `"__proto__"` key (from `JSON.parse`) is cloned as an own key and never changes the clone's prototype.

```ts
areEqual({ a: 1 }, { a: 1 });        // true
areEqual([1, 2, 3], [1, 2, 3]);      // true
areEqual([1, 2, 3], [3, 2, 1]);      // false — order matters

areEqual(new Date(0), new Date(0));  // true
areEqual(/abc/g, /abc/g);            // true
areEqual(new Set([1, 2]), new Set([2, 1])); // true (Set equality)

const a: any = { x: 1 }; a.self = a;
const b: any = { x: 1 }; b.self = b;
areEqual(a, b);                       // true — circular-safe
```

> This is a **value comparator**, not a type/shape predicate. For predicates like `isEmpty` / `isPlainObject`, use `@mongez/supportive-is`.

## `shuffle` — Fisher–Yates

```ts
shuffle<T>(value: T[], options?: { mutate?: boolean }): T[]
shuffle(value: string, options?: { mutate?: boolean }): string
```

Non-mutating by default. Pass `{ mutate: true }` to shuffle the array in place. Positions come from the CSPRNG (`crypto.getRandomValues`, with rejection sampling), so the order is unbiased, unpredictable and unseedable (`Random.seed` has no effect on it). Without a CSPRNG (for example Hermes with no polyfill) it falls back to `Math.random` rather than throwing.

```ts
shuffle([1, 2, 3, 4]);                  // e.g. [3, 1, 4, 2]; original untouched
shuffle("hello");                        // e.g. "lehlo"
shuffle(arr, { mutate: true });          // shuffles in place, returns arr
```

## `coalesce` — first non-nullish

```ts
coalesce<T>(...values: Array<T | null | undefined>): T | undefined
```

Returns the first value that isn't `null` or `undefined`. **Falsy-but-defined values** (`0`, `""`, `false`, `NaN`) pass through — unlike `||`.

```ts
coalesce(null, undefined, "first");  // "first"
coalesce(undefined, 0, "x");         // 0
coalesce(undefined, "", "x");        // ""
coalesce(null, undefined);           // undefined
```

---

# Random

> **Auto-trigger:** code imports `Random`, `RandomDateOptions`, or `WeightedItem` from `@mongez/reinforcements`, or calls `Random.int`/`Random.float`/`Random.bool`/`Random.string`/`Random.id`/`Random.uuid`/`Random.nanoid`/`Random.token`/`Random.date`/`Random.color`/`Random.pick`/`Random.sample`/`Random.weighted`/`Random.seed`; user asks "how do I generate a UUID / nanoid / random integer / pick a random element / seed randomness for tests / make a weighted random choice"; `import { Random } from "@mongez/reinforcements"`.
> **Skip when:** cryptographic-strength randomness for security (use `crypto.randomBytes`, `crypto.subtle`); `nanoid`/`uuid` npm packages when not going through `@mongez/reinforcements`; seedable PRNGs for simulations needing different distributions (use a stats library).

Namespace class — every method is `public static`. Not instantiable.

```ts
import { Random, type RandomDateOptions, type WeightedItem } from "@mongez/reinforcements";
```

## Seeding (reproducible mode)

```ts
Random.seed(seed?: number): void
```

Switches the RNG to a deterministic mulberry32 PRNG. Call with no args (or `undefined`) to restore `Math.random`. It does not affect `shuffle`, which always uses the CSPRNG (falling back to `Math.random`).

```ts
Random.seed(42);
const a = Random.int(1, 1000);

Random.seed(42);
const b = Random.int(1, 1000);

a === b;          // true
Random.seed();    // back to Math.random
```

Great for fixture-based tests:

```ts
beforeEach(() => Random.seed(123));
afterEach(()  => Random.seed());
```

`seed` only affects `int` / `float` / `bool` / `pick` / `sample` / `weighted` / `date` / `color`. **`string`, `id`, `nanoid`, `token`, and `uuid` are CSPRNG-backed and ignore the seed entirely** — see below.

## Primitives

```ts
Random.int(min?: number, max?: number): number          // default [1, 9999999], inclusive
Random.float(min?: number, max?: number, precision?: number): number  // default [0, 1)
Random.bool(): boolean
```

```ts
Random.int(1, 10);          // e.g. 7
Random.float(0, 1, 2);      // e.g. 0.42
Random.bool();              // true or false
```

## Strings & ids

```ts
Random.string(length?: number): string                  // alphanumeric, default 32
Random.id(length?: number, startsWith?: string): string // default 6, "el-"
Random.uuid(): string                                   // RFC 4122 v4 (crypto.randomUUID when available)
Random.nanoid(size?: number): string                    // URL-safe, default 21
Random.token(bytes?: number): string                    // crypto-backed hex, default 16
```

```ts
Random.string(8);          // e.g. "Xk2pQ9aZ"
Random.id();               // e.g. "el-X4kP2a"
Random.id(4, "user-");     // e.g. "user-q7Zw"
Random.uuid();             // "0a8b40e1-d3ef-4d2e-87f4-1a8b40e1d3ef"
Random.nanoid(10);         // "rH3kQ_pX7a"
Random.token(16);          // 32-char hex
```

**`string`, `id`, `nanoid`, and `token` are always CSPRNG-backed** (`crypto.getRandomValues`) — never drawn from the seedable PRNG, even under `Random.seed(n)`. `uuid` uses `crypto.randomUUID` when available, otherwise `crypto.getRandomValues`. All five **throw `"No CSPRNG available: crypto.getRandomValues is required"`** on a runtime with no WebCrypto (pre-ES2020 browsers, Node < 15 without a `crypto` global) — they never silently degrade to a predictable generator.

> **Breaking change (v4):** prior to v4, `string`/`id`/`nanoid`/`token`/`uuid` fell back to the internal PRNG and therefore *could* be seeded/reproduced under test. That fallback was a security bug — a predictable "random" identifier is exploitable wherever it's used as a token, invite code, or session-adjacent value. If you relied on seeded output from these five methods for fixtures, generate fixture values a different way (a fixed literal, a counter, or an explicitly-seeded UUID library) — do not reach for `Random.seed()` expecting them to comply.

Any length works: CSPRNG bytes are drawn in batches of at most 65,536 bytes (the `getRandomValues` limit), so `Random.string(100_000)` and `Random.token(100_000)` do not throw.

**Use for ids only**, not for cryptographic key/token material beyond opaque identifiers — for anything security-sensitive, prefer the Web Crypto API directly and document the derivation.

## Dates & colors

```ts
Random.date(options?: RandomDateOptions): Date
type RandomDateOptions = { min?: Date; max?: Date };

Random.color(): string  // "#rrggbb", always 6 hex digits
```

```ts
Random.date({ min: new Date("2020-01-01"), max: new Date("2024-12-31") });
Random.color(); // e.g. "#1f3a8a"
```

## Pick / sample / weighted

```ts
Random.pick<T>(array: readonly T[]): T | undefined
Random.sample<T>(array: readonly T[], n: number): T[]                          // n unique elements
Random.weighted<T>(items: readonly WeightedItem<T>[]): T | undefined
type WeightedItem<T> = { value: T; weight: number };
```

```ts
Random.pick(["a", "b", "c"]);              // e.g. "b"
Random.sample([1, 2, 3, 4, 5], 3);         // e.g. [3, 1, 5]
Random.weighted([
  { value: "free",    weight: 80 },
  { value: "premium", weight: 19 },
  { value: "vip",     weight:  1 },
]);                                         // weighted choice
```

`sample` returns at most `array.length` items. Negative weights in `weighted` are clamped to `0`; if every weight is `0` returns `undefined`.

## Gotchas

- `Random` is **not instantiable** — `new Random()` is a TS error. Use the static methods directly.
- The legacy aliases `Random.integer` / `Random.boolean` from v2 are **removed**. Use `Random.int` / `Random.bool`.
- Seeded mode persists until cleared — call `Random.seed()` (no args) in `afterEach` to avoid cross-test contamination. Seeding has **no effect** on `string` / `id` / `nanoid` / `token` / `uuid`.
- `Random.string` / `id` / `nanoid` / `token` / `uuid` **throw** on a runtime without `crypto.getRandomValues` — wrap calls in test environments that stub out WebCrypto, or polyfill it.

---

# Lazy

> **Auto-trigger:** code imports `lazy`, `isLazy`, `Lazy`, or `LazyAsync` from `@mongez/reinforcements`, or calls `lazy.async()` / `lazy.from()`; user asks "how do I break a circular import / defer initialization / memoize a computed value lazily"; `import { lazy, isLazy } from "@mongez/reinforcements"`.
> **Skip when:** React.lazy code-splitting (different concept — component dynamic imports); plain `memoize()` for pure-function caching (use @mongez/reinforcements-functions instead); one-shot init that just needs `once()` from the functions skill.

Memoised deferred values. The flagship utility of the package — the unique tool for breaking ES-module circular imports.

```ts
import { lazy, isLazy, type Lazy, type LazyAsync } from "@mongez/reinforcements";
```

## `lazy(producer)`

```ts
lazy<T>(producer: () => T): Lazy<T>

type Lazy<T> = {
  resolve(): T;          // compute (once) and return the cached value
  reset(): void;         // drop the cache; next resolve() recomputes
  isResolved(): boolean; // has resolve() been called?
  peek(): T | undefined; // cached value without forcing computation
};
```

The producer **is not invoked** until the first `resolve()`. The result is then memoised.

```ts
const config = lazy(() => loadHeavyConfig());

config.resolve();   // computes
config.resolve();   // cached, no recomputation
config.reset();     // forget cached value
config.resolve();   // recomputes
config.peek();      // returns cached value or undefined
config.isResolved(); // true / false
```

## Why it exists: circular imports

JavaScript closures capture **variable bindings**, not values. When Module A imports Module B which imports Module A, the value that A wants from B might not be defined yet at module-init time. `lazy()` defers the reference resolution to call time.

```ts
// In a module that creates a circular dep:
const service = lazy(() => Service); // Service is undefined right now — fine

export function handler() {
  return service.resolve().run();    // Service is guaranteed to exist by this point
}
```

## `lazy.async(producer)`

```ts
lazy.async<T>(producer: () => Promise<T>): LazyAsync<T>

type LazyAsync<T> = {
  resolve(): Promise<T>;
  reset(): void;
  isResolved(): boolean;
  peek(): Promise<T> | undefined;
};
```

Same shape as `lazy`, but the cached value is a `Promise<T>`.

```ts
const user = lazy.async(() => fetch("/api/me").then(r => r.json()));

await user.resolve();  // fetches
await user.resolve();  // returns the same cached promise — no refetch
user.reset();
await user.resolve();  // refetches
```

## `lazy.from(value)`

```ts
lazy.from<T>(value: T): Lazy<T>
```

Pre-resolved lazy — for tests or for API symmetry where a `Lazy<T>` is expected but the value is already known.

```ts
const ref = lazy.from(42);
ref.resolve();      // 42
ref.isResolved();   // true
ref.reset();        // no-op for pre-resolved lazies
```

## `isLazy(value)`

```ts
isLazy<T = unknown>(value: unknown): value is Lazy<T>
```

Type guard. Returns `true` for both `lazy()` and `lazy.async()` results.

```ts
if (isLazy<number>(value)) {
  value.resolve(); // typed as number
}
```

## Idioms

**Resetting on config reload:**

```ts
const cachedConfig = lazy(() => parseConfigFile());

watchConfigFile(() => {
  cachedConfig.reset();
});

export function getSetting(key: string) {
  return cachedConfig.resolve()[key]; // re-parses on first call after reload
}
```

**Disambiguating "not yet resolved" from "resolved to undefined":**

```ts
const maybe = lazy(() => undefined);

maybe.isResolved();  // false
maybe.peek();        // undefined
maybe.resolve();
maybe.isResolved();  // true
maybe.peek();        // undefined  ← but isResolved() distinguishes the cases
```

**Error retry:** producers that throw are not memoised; the next `resolve()` re-invokes the producer.

---

# Function utilities

> **Auto-trigger:** code imports `debounce`, `throttle`, `memoize`, `once`, `after`, `before`, `pipe`, `compose`, `tap`, `curry`, `partial`, `partialRight`, `noop`, `identity`, `constant`, `negate`, or `escapeRegex` from `@mongez/reinforcements`; user asks "how do I debounce / throttle / memoize / cache / pipe / curry a function"; `import { debounce, throttle, memoize, pipe } from "@mongez/reinforcements"`.
> **Skip when:** @mongez/reinforcements-async handles promise-returning rate limiting (`debounceAsync`, `retry`, `timeout`) — use that skill for async equivalents; lodash/ramda equivalents without `@mongez/reinforcements` imports; React `useCallback`/`useMemo` hooks (component-scoped, not these utilities).

Rate-limiting, memoization, composition, currying, tiny FP primitives.

```ts
import {
  debounce, throttle, memoize, once, after, before,
  pipe, compose, tap, curry, partial, partialRight,
  noop, identity, constant, negate, escapeRegex, attempt,
} from "@mongez/reinforcements";
```

## Rate-limiting

#### `debounce`

```ts
debounce<T>(fn: T, wait: number, options?: {
  leading?: boolean;   // default false
  trailing?: boolean;  // default true
  maxWait?: number;    // force invocation at this cap, even if input keeps coming
}): Debounced<T>

type Debounced<T> = T & {
  cancel(): void;   // drop any pending invocation
  flush(): void;    // invoke the pending call immediately
  pending(): boolean;
};
```

```ts
const save = debounce(payload => api.save(payload), 500, { maxWait: 3000 });

input.addEventListener("input", e => save(e.target.value));
button.addEventListener("click", () => save.flush());
window.addEventListener("beforeunload", () => save.cancel());
```

#### `throttle`

```ts
throttle<T>(fn: T, wait: number, options?: {
  leading?: boolean;   // default true
  trailing?: boolean;  // default true
}): Throttled<T>

type Throttled<T> = T & { cancel(): void; flush(): void; pending(): boolean };
```

```ts
const onScroll = throttle(() => layout(), 100);
window.addEventListener("scroll", onScroll);
```

## Caching

#### `memoize`

```ts
memoize<T>(fn: T, options?: {
  resolver?: (...args: Parameters<T>) => string; // default JSON.stringify(args)
  ttl?: number;                                  // ms; default Infinity
  maxSize?: number;                              // LRU bound; default 1000, Infinity = unbounded, 0 = no caching
}): Memoized<T>

type Memoized<T> = T & { clear(): void; forget(key: string): void };
```

```ts
const lookup = memoize((id: string) => db.users.find(id), { ttl: 60_000 });

lookup("u1");                       // hits DB
lookup("u1");                       // cached
lookup.forget(JSON.stringify(["u1"])); // surgical invalidation (default key = JSON.stringify(args))
lookup.clear();                     // nuke everything
```

The cache is bounded: past `maxSize` the least recently used entry is evicted (a hit refreshes an entry). An expired `ttl` entry is recomputed on its next call, and all expired entries are swept from the cache at most once per `ttl` period, so memory does not grow with dead entries. The default key is `JSON.stringify(args)` with `undefined` kept apart from `null` (an `undefined` argument, or a string starting with `"\u0000"`, gets an escaped key; every other argument keeps the plain `JSON.stringify` key, so `forget(JSON.stringify([...]))` still works). Arguments the default cannot serialize (cyclic objects, `BigInt`) skip the cache and call `fn` directly. A custom `resolver` is used as-is (its errors propagate).

Custom key:

```ts
const cached = memoize(
  (a: User, b: User) => similarity(a, b),
  { resolver: (a, b) => `${a.id}-${b.id}` },
);
```

## Call-count gating

```ts
once<T>(fn: T): T                                   // run once, cache result forever
after<T>(n: number, fn: T): (...args) => R | undefined  // only invokes after N-th call
before<T>(n: number, fn: T): (...args) => R | undefined // up to N times; later calls return last result
```

```ts
const init = once(() => expensiveSetup());
init(); init(); init(); // expensiveSetup runs once

const onAllDone = after(3, () => render());
onAllDone(); onAllDone(); onAllDone(); // render() on the third call

const tryConnect = before(3, () => connect());
// up to 3 actual connect() calls; further calls return the last result
```

## Composition

#### `pipe` / `compose`

```ts
pipe<A>(value: A): A
pipe<A, B>(value: A, fn1: (a: A) => B): B
pipe<A, B, C>(value: A, fn1: (a: A) => B, fn2: (b: B) => C): C
// …up to 4 typed steps; variadic fallback after that

compose<A, B, C>(fn2: (b: B) => C, fn1: (a: A) => B): (a: A) => C
// right-to-left
```

```ts
pipe(2, n => n + 1, n => n * 10);  // 30

const shout = compose(
  (s: string) => s + "!",
  (s: string) => s.toUpperCase(),
);
shout("hi");  // "HI!"
```

#### `tap` / `tap.with`

```ts
tap<T>(value: T, sideEffect: (value: T) => void): T
tap.with<T>(sideEffect: (value: T) => void): (value: T) => T
```

Side-effect probe. `tap.with` returns a pipeline-friendly identity-with-side-effect.

```ts
pipe(value, trim, tap.with(console.log), toSnakeCase);
```

## Currying & partial application

```ts
curry(fn: (...args) => R): any
partial<T>(fn: T, ...preset): (...rest) => ReturnType<T>
partialRight<T>(fn: T, ...preset): (...rest) => ReturnType<T>
```

```ts
const add = curry((a: number, b: number, c: number) => a + b + c);
add(1)(2)(3);       // 6
add(1, 2)(3);       // 6
add(1, 2, 3);       // 6

const greet = (greeting: string, name: string) => `${greeting}, ${name}`;
const hello = partial(greet, "Hello");
hello("Ada");       // "Hello, Ada"

const divide = (a: number, b: number) => a / b;
const halve = partialRight(divide, 2);
halve(10);          // 5
```

## Tiny FP primitives

```ts
noop(): void                                    // does nothing
identity<T>(value: T): T                        // returns argument
constant<T>(value: T): () => T                  // returns a function that always yields value
negate<T>(predicate: T): (...args) => boolean   // inverts a predicate
```

```ts
items.filter(identity);              // drop falsy values
events.on("data", noop);             // explicitly ignore
const always42 = constant(42);
const isOdd = negate((n: number) => n % 2 === 0);
```

## `escapeRegex`

```ts
escapeRegex(string: string): string
```

Escape regex meta-characters so a literal string can be used in a `RegExp`.

```ts
new RegExp(escapeRegex("a.b+c")); // matches the literal "a.b+c"
```

## `attempt`

```ts
attempt<T, F = undefined>(fn: () => Promise<T>, fallback?: F): Promise<T | F>
attempt<T, F = undefined>(fn: () => T, fallback?: F): T | F
```

Run `fn` and return its result; if it throws or rejects, return `fallback` (or `undefined`). Works for sync and async functions — a promise-returning `fn` yields a promise. Removes one-off try/catch boilerplate.

```ts
const config = attempt(() => JSON.parse(raw), {});
const user = await attempt(() => api.getUser(id), null);
```

---

# Async

> **Auto-trigger:** code imports `sleep`, `retry`, `timeout`, `pProps`, `pAll`, `pAllSettled`, `pMap`, `pSeries`, `pFilter`, `defer`, or `debounceAsync` from `@mongez/reinforcements`; user asks "how do I retry with backoff / race a promise against a timeout / limit concurrency / debounce an async call"; `import { sleep, retry, timeout, pMap, defer } from "@mongez/reinforcements"`.
> **Skip when:** @mongez/reinforcements-functions handles sync `debounce`/`throttle`/`memoize` — use this skill only for promise-returning helpers; raw `Promise.all`/`Promise.race` usage without `@mongez/reinforcements` imports; HTTP client features (fetch wrappers, interceptors) belong to a request library, not this package.

Promise-based control flow: sleep, retry, timeout, bounded concurrent map/filter/series, defer, async debounce.

```ts
import {
  sleep, retry, retryable, timeout,
  pAll, pAllSettled, pMap, pSeries, pFilter, pReduce,
  poll, waitFor, defer, debounceAsync,
} from "@mongez/reinforcements";
```

## `sleep`

```ts
sleep(ms: number): Promise<void>
sleep<T>(ms: number, value: T): Promise<T>
```

```ts
await sleep(100);
const ready = await sleep(50, "ok"); // "ok"
```

## `retry`

```ts
retry<T>(fn: () => Promise<T> | T, options?: {
  attempts?: number;                                          // default 3
  delay?: number;                                             // base ms; default 0
  backoff?: "linear" | "exponential"                          // default "linear"
         | ((attempt: number, baseDelay: number) => number);  // or a custom fn
  maxDelay?: number;                                          // ceiling on the computed delay
  jitter?: boolean | "full" | "equal";                        // spread delays; default false
  onError?: (error: unknown, attempt: number) => void;        // observe (1-based attempt)
  shouldRetry?: (error: unknown, attempt: number)             // decide; false = stop now
             => boolean | Promise<boolean>;
  signal?: AbortSignal;                                       // cancel between/during attempts
}): Promise<T>
```

Throws the **last** error if all attempts fail. All options are optional and default to today's behaviour — nothing here is a breaking change.

```ts
const data = await retry(() => fetchUser(id), {
  attempts: 5,
  delay: 200,
  backoff: "exponential",  // 200, 400, 800, 1600 ms between attempts
  onError: (err, attempt) => log(`attempt ${attempt} failed`, err),
});
```

**Bail out on non-retryable errors** with `shouldRetry` — observe with `onError`, decide with `shouldRetry` (called in that order):

```ts
await retry(() => placeOrder(input), {
  attempts: 3,
  delay: 500,
  shouldRetry: err => !(err instanceof ValidationError), // don't retry 4xx
});
```

**Avoid thundering herd + cap the wait** with `jitter` and `maxDelay`:

```ts
await retry(() => fetch(url), {
  attempts: 6,
  delay: 100,
  backoff: "exponential",
  maxDelay: 2_000,   // never wait more than 2s, even as backoff grows
  jitter: "full",    // randomise each delay across [0, computed]
});
```

`jitter: "full"` (or `true`) → `random(0, delay)`; `"equal"` → `delay/2 + random(0, delay/2)`. Jitter draws from the package's seedable `Random`, so `Random.seed(n)` makes the schedule reproducible in tests.

**Cancel a long retry loop** with an `AbortSignal` — a pending delay is raced against the signal, so an abort resolves promptly instead of waiting the delay out:

```ts
const controller = new AbortController();
const promise = retry(poll, { attempts: 10, delay: 1_000, signal: controller.signal });
controller.abort(); // rejects with signal.reason
```

## `retryable`

Pre-bind retry options to a function, returning a reusable wrapper so you don't re-pass options at every call site:

```ts
retryable<A, T>(fn: (...args: A) => Promise<T> | T, options?: RetryOptions): (...args: A) => Promise<T>
```

```ts
const fetchUser = retryable(getUser, { attempts: 4, backoff: "exponential" });
await fetchUser(id);
```

> **Tip:** `exponential` backoff with many `attempts` and no `maxDelay` can produce very long waits — set `maxDelay` to bound the worst case.

## `timeout`

```ts
timeout<T>(promise: Promise<T>, ms: number, message?: string): Promise<T>
```

Races `promise` against a timer; rejects with `new Error(message)` if the timer wins.

```ts
const result = await timeout(fetch(url), 5_000, "Request too slow");
```

Combines well with `retry`:

```ts
await retry(
  () => timeout(fetch(url), 3_000),
  { attempts: 3, delay: 500, backoff: "exponential" },
);
```

## `pProps` — parallel object destructuring

```ts
pProps<T extends Record<string, unknown>>(
  object: T,
): Promise<{ [K in keyof T]: Awaited<T[K]> }>
```

Run an object's worth of promises in parallel and resolve to an object with the same keys but unwrapped values. Modelled on Bluebird's `Promise.props`. Non-promise values pass through unchanged.

```ts
const { user, settings, home } = await pProps({
  user:     getUserFromDB(),
  settings: loadSettingsAsync(),
  home:     getHome(),
});

// Mixed promises and plain values are fine:
await pProps({ a: 1, b: Promise.resolve(2) }); // { a: 1, b: 2 }
```

Rejects on the first rejected promise (same semantics as `Promise.all`).

## `pAll` / `pAllSettled`

```ts
pAll<T extends readonly unknown[]>(
  promises: readonly [...{ [K in keyof T]: T[K] | Promise<T[K]> }],
): Promise<T>

pAllSettled<T extends readonly unknown[]>(
  promises: readonly [...{ [K in keyof T]: T[K] | Promise<T[K]> }],
): Promise<{ [K in keyof T]: PromiseSettledResult<T[K]> }>
```

Typed tuple-preserving wrappers around `Promise.all` / `Promise.allSettled`.

```ts
const [user, posts] = await pAll([fetchUser(), fetchPosts()]);
// user: User, posts: Post[]
```

## Bounded concurrency

#### `pMap`

```ts
pMap<T, U>(
  items: readonly T[],
  mapper: (item: T, index: number) => Promise<U> | U,
  options?: {
    concurrency?: number;   // default Infinity
    stopOnError?: boolean;  // default true
  },
): Promise<U[]>
```

Preserves input order in the output. With `stopOnError: false`, every error is collected and the first one is thrown after all items complete.

```ts
const docs = await pMap(urls, fetch, { concurrency: 5 });
```

#### `pSeries`

```ts
pSeries<T, U>(items: readonly T[], mapper: (item, index) => Promise<U> | U): Promise<U[]>
```

Strictly sequential. Stops at the first thrown error.

```ts
await pSeries(migrations, m => runMigration(m));
```

#### `pFilter`

```ts
pFilter<T>(
  items: readonly T[],
  predicate: (item: T, index: number) => Promise<boolean> | boolean,
  options?: { concurrency?: number },
): Promise<T[]>
```

```ts
const reachable = await pFilter(urls, u => ping(u), { concurrency: 4 });
```

## `defer`

```ts
defer<T = void>(): {
  promise: Promise<T>;
  resolve: (value: T | PromiseLike<T>) => void;
  reject: (reason?: unknown) => void;
}
```

Externally resolvable promise — useful for bridging callback APIs.

```ts
function whenReady() {
  const d = defer<void>();
  emitter.once("ready", () => d.resolve());
  emitter.once("error", err => d.reject(err));
  return d.promise;
}
```

## `debounceAsync`

```ts
debounceAsync<T extends (...args: any[]) => Promise<any>>(
  fn: T,
  wait: number,
): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>
```

Async-aware debounce: every call returns a promise; bursts collapse into a single `fn` invocation; **all the burst's promises resolve with the same final result**.

```ts
const search = debounceAsync(
  (q: string) => fetch(`/search?q=${q}`).then(r => r.json()),
  250,
);

const a = search("a");
const b = search("ab");
const c = search("abc");
// 250ms later: one fetch("abc"); a, b, c all resolve with that result
```

## `poll`

```ts
poll<T>(fn: (attempt: number) => Promise<T> | T, options?: {
  interval?: number;                                // ms between attempts; default 1000
  timeout?: number;                                 // give up after ms; default none
  attempts?: number;                                // max attempts; default none
  until?: (result: T, attempt: number) => boolean;  // stop condition; default: result is truthy
  signal?: AbortSignal;                             // abort early
}): Promise<T>
```

Repeatedly call `fn` until `until(result)` is truthy, then resolve with that result. Rejects on `timeout`, the `attempts` cap, or abort. Ideal for polling job status or readiness.

```ts
const job = await poll(() => api.getJob(id), {
  interval: 2_000,
  timeout: 60_000,
  until: job => job.status === "done",
});
```

## `waitFor`

```ts
waitFor(
  condition: (attempt: number) => Promise<boolean> | boolean,
  options?: WaitForOptions, // = Omit<PollOptions, "until">
): Promise<void>
```

Convenience wrapper around `poll` for boolean readiness checks — resolves once `condition` is truthy.

```ts
await waitFor(() => queue.isEmpty(), { interval: 100, timeout: 5_000 });
```

## `pReduce`

```ts
pReduce<T, A>(
  items: readonly T[],
  reducer: (acc: A, item: T, index: number) => Promise<A> | A,
  initial: A,
): Promise<A>
```

Sequential async reduce — awaits the accumulator between steps. The async sibling of `Array.prototype.reduce`.

```ts
const total = await pReduce(ids, async (sum, id) => sum + (await fetchScore(id)), 0);
```

---

# Arrays

> **Auto-trigger:** code imports `chunk`, `range`, `unique`, `pluck`, `groupBy`, `countBy`, `count`, `sum`, `average`, `avg`, `median`, `min`, `max`, `even`, `odd`, `evenIndexes`, `oddIndexes`, `pushUnique`, or `unshiftUnique` from `@mongez/reinforcements`; user asks "how do I dedupe / chunk / group / count / sum / average / pluck from an array"; file does aggregation or reshaping over object arrays.
> **Skip when:** richer collection ops (`partition`, `keyBy`, `sortBy`, `intersection`, `where`, pagination) — use `mongez-collection-*` skills instead; plain native `Array` methods without `@mongez/reinforcements` imports; React-specific list rendering or virtualization.

Lightweight, tree-shakable array helpers. Every function imports from the package root — `import { unique } from "@mongez/reinforcements"`. For a chainable collection API and heavier operations (`sortBy`, `where`, `flatMap`, …) reach for [`@mongez/collection`](/collection/overview/).

## `chunk()`

Split an array (or string) into groups of `size`. The final group holds whatever is left over.

```ts
chunk<T>(array: T[] | string, size: number): T[][]
```

```ts
chunk([1, 2, 3, 4, 5], 2);  // [[1, 2], [3, 4], [5]]
chunk([1, 2, 3], 0);        // [] — size must be a positive integer
chunk("abcdef", 2);         // [["a", "b"], ["c", "d"], ["e", "f"]]
```

## `range()`

Build an inclusive array of numbers from `min` to `max`.

```ts
range(min: number, max: number): number[]
```

```ts
range(1, 5);   // [1, 2, 3, 4, 5]
range(0, 0);   // [0]
```

## `unique()`

Remove duplicate values. Pass a `key` to dedupe an array of objects by a property — the result is the plucked unique values for that key.

```ts
unique<T>(array: T[], key?: string): T[]
```

```ts
unique([1, 1, 2, 3, 3]);                          // [1, 2, 3]
unique([{ id: 1 }, { id: 1 }, { id: 2 }], "id");  // [1, 2]
```

## `pluck()`

Project a single property (or a subset of properties) out of an array of objects. Dot-notation paths work for nested values.

```ts
pluck(array: any[], key?: string | string[]): any[]
```

```ts
pluck([{ name: "Ada" }, { name: "Bob" }], "name"); // ["Ada", "Bob"]
pluck([{ a: 1, b: 2 }, { a: 3, b: 4 }], ["a"]);    // [{ a: 1 }, { a: 3 }]
pluck(users, "address.city");                       // nested path
```

## `groupBy()`

Group an array of objects by one or more keys. Each group is an object with the key value(s) plus a `data` array of its members — rename `data` via the third argument.

```ts
groupBy(array: object[], key: string | string[], listAs?: string): object[]
```

```ts
groupBy(students, "class");             // [{ class: "A", data: [...] }, ...]
groupBy(students, ["class", "grade"]);  // multi-key grouping
groupBy(students, "class", "items");    // rename "data" → "items"
groupBy(items, "__proto__");            // the group stays an own key (not dropped)
```

## `countBy()`

Tally how many items fall under each value of `key`. Returns a `value → count` map.

```ts
countBy(array: any[], key: string): Record<string, number>
```

```ts
countBy([{ type: "a" }, { type: "b" }, { type: "a" }], "type");
// { a: 2, b: 1 }
```

## `count()`

Count items matching a condition — either items with a defined value at a dot-notation path, or items passing a predicate.

```ts
count(array: any[], key: string | ((item) => boolean)): number
```

```ts
count(items, "name");               // items that have a defined "name"
count(items, item => item.active);  // items passing the predicate
```

## `sum()`

Add up the numbers in an array. Pass a dot-notation `key` to sum a property across an array of objects.

```ts
sum(array: any[], key?: string): number
```

```ts
sum([1, 2, 3]);             // 6
sum(orders, "total.price"); // sum of total.price across orders
```

## `average()` / `avg()`

Arithmetic mean of the values (or of a keyed property). `avg` is a shorthand alias.

```ts
average(array: any[], key?: string): number   // alias: avg
```

```ts
average([2, 4, 6]); // 4
avg(users, "age");  // mean age
```

> Average of an empty array is `NaN` — guard before displaying.

## `median()`

The middle value once sorted (mean of the two middle values for even-length arrays).

```ts
median(array: any[], key?: string): number
```

```ts
median([1, 2, 3, 4]); // 2.5
median([3, 1, 2]);    // 2 — the input array is not mutated
```

## `min()` / `max()`

Smallest / largest value, optionally by a dot-notation key.

```ts
min(array: any[], key?: string): number
max(array: any[], key?: string): number
```

```ts
min([5, 2, 9]);   // 2
max(users, "age"); // largest age
```

> `min` / `max` of an empty array return `0`.

## `even()` / `odd()`

Filter to elements whose **value** is even / odd. With a `key`, tests that property instead.

```ts
even(array: any[], key?: string): any[]
odd(array: any[], key?: string): any[]
```

```ts
even([1, 2, 3, 4]);  // [2, 4]
odd([1, 2, 3, 4]);   // [1, 3]
even(items, "age");  // items whose age is even
```

## `evenIndexes()` / `oddIndexes()`

Filter by **position** rather than value — elements sitting at even / odd indices.

```ts
evenIndexes<T>(array: T[]): T[]   // indices 0, 2, 4, …
oddIndexes<T>(array: T[]): T[]    // indices 1, 3, 5, …
```

```ts
evenIndexes(["a", "b", "c", "d"]); // ["a", "c"]
oddIndexes(["a", "b", "c", "d"]);  // ["b", "d"]
```

## `pushUnique()` / `unshiftUnique()`

Append / prepend items only when they aren't already present.

```ts
pushUnique<T>(array: T[], ...items: T[]): T[]
unshiftUnique<T>(array: T[], ...items: T[]): T[]
```

```ts
const arr = [1, 2];
pushUnique(arr, 2, 3);    // [1, 2, 3]    — 2 was skipped
unshiftUnique(arr, 0, 1); // [0, 1, 2, 3] — 1 was skipped
```

> **These mutate the input array** (and return the same reference). Reach for them when you have a stable array you want to grow without duplicates. For a non-mutating dedupe, use [`unique()`](#unique).

## `partition()`

Split an array into two groups by a predicate: `[pass, fail]`. Single pass, original order preserved.

```ts
partition<T>(array: T[], predicate: (item: T, index: number) => unknown): [T[], T[]]
```

```ts
partition([1, 2, 3, 4], n => n % 2 === 0);  // [[2, 4], [1, 3]]
const [active, archived] = partition(users, u => u.active);
```

## `keyBy()`

Index an array into an object keyed by each item's `key` — a dot-notation string path or a selector function. Last item wins on key collision.

```ts
keyBy<T>(array: T[], key: string | ((item: T, index: number) => PropertyKey)): Record<string, T>
```

```ts
keyBy([{ id: 1 }, { id: 2 }], "id"); // { "1": { id: 1 }, "2": { id: 2 } }
keyBy(users, user => user.email);    // keyed by email
```

## `intersection()`

Unique values present in **every** array (set intersection). Order follows the first array; values compared by `SameValueZero`.

```ts
intersection<T>(...arrays: T[][]): T[]
```

```ts
intersection([1, 2, 3], [2, 3, 4], [3, 2]); // [2, 3]
```

## `difference()`

Unique values from the first array that appear in **none** of the others (set difference). Order follows the first array.

```ts
difference<T>(array: T[], ...others: T[][]): T[]
```

```ts
difference([1, 2, 3, 4], [2, 4]); // [1, 3]
difference([1, 2, 3], [2], [3]);  // [1]
```

## `union()`

Concatenate all arrays and return the unique values, preserving first-seen order (set union).

```ts
union<T>(...arrays: T[][]): T[]
```

```ts
union([1, 2], [2, 3], [3, 4]); // [1, 2, 3, 4]
```

## `zip()`

Combine several arrays into tuples paired by index. Length matches the **longest** input; missing slots are `undefined`.

```ts
zip(...arrays: T[][]): Array<[...tuple]>
```

```ts
zip([1, 2], ["a", "b"]); // [[1, "a"], [2, "b"]]
zip([1], ["a", "b"]);    // [[1, "a"], [undefined, "b"]]
```

## `unzip()`

The inverse of `zip` — turn an array of tuples back into a tuple of arrays grouped by position.

```ts
unzip<T>(array: T[][]): (T | undefined)[][]
```

```ts
unzip([[1, "a"], [2, "b"]]); // [[1, 2], ["a", "b"]]
```

---

# Types

> **Auto-trigger:** code imports `Path`, `PathValue`, `DeepPartial`, `DeepRequired`, `DeepReadonly`, `DeepMutable`, `Prettify`, `UnionToIntersection`, `Branded`, `Nullable`, `Maybe`, `Awaitable`, `NonEmptyArray`, `GenericObject`, `AlphaNumeric`, or `Primitive` as a `type` from `@mongez/reinforcements`; user asks "how do I type a dot-notation path / make all properties recursively optional / create a branded nominal type / flatten an intersection in hover / convert a union to an intersection"; `import type { Path, PathValue, DeepPartial } from "@mongez/reinforcements"`.
> **Skip when:** runtime utilities (`get`, `pick`, `omit`, etc.) — use @mongez/reinforcements-objects for those; `type-fest` or other third-party type-utility libraries when not going through `@mongez/reinforcements`; Zod/Valibot runtime schema definitions (different layer).

TypeScript-only exports — zero runtime cost. Import as types:

```ts
import type {
  Path, PathValue,
  DeepPartial, DeepRequired, DeepReadonly, DeepMutable,
  Prettify, UnionToIntersection, Branded,
  Nullable, Maybe, Awaitable, NonEmptyArray,
  GenericObject, AlphaNumeric, Primitive,
} from "@mongez/reinforcements";
```

## Dot-notation paths

```ts
type Path<T, Depth = 6>          // union of every legal dot-notation path
type PathValue<T, P extends string> // resolved value type at path P
```

```ts
type User = {
  id: number;
  profile: { email: string; addresses: { city: string }[] };
};

type UserPath = Path<User>;
// "id" | "profile" | "profile.email" | "profile.addresses" | "profile.addresses.${number}" | ...

type Email = PathValue<User, "profile.email">; // string
type City  = PathValue<User, "profile.addresses.0.city">; // string
```

Used internally to type `get(obj, path)` overloads.

## Recursive transforms

```ts
type DeepPartial<T>    // all properties (recursively) optional
type DeepRequired<T>   // all properties (recursively) required
type DeepReadonly<T>   // all properties (recursively) readonly
type DeepMutable<T>    // strips readonly recursively
```

Each preserves primitives, `Date`, `RegExp`, `Function`, `Map<K,V>`, and `Set<T>` rather than recursing into them.

```ts
type Config = { api: { url: string; retries: number } };

type DraftConfig = DeepPartial<Config>;
// { api?: { url?: string; retries?: number } }

type FrozenConfig = DeepReadonly<Config>;
// { readonly api: { readonly url: string; readonly retries: number } }
```

## Display & combinators

```ts
type Prettify<T>            // flatten intersections in hover tooltips
type UnionToIntersection<U> // U union → I intersection (variadic typings)
```

```ts
type Combined = Prettify<{ a: 1 } & { b: 2 }>;
// hovers as { a: 1; b: 2 }  instead of  { a: 1 } & { b: 2 }
```

## Nominal types

```ts
type Branded<T, B extends string> = T & { readonly __brand: B }
```

Distinguish lookalike primitives at the type level.

```ts
type UserId = Branded<string, "UserId">;
type Email  = Branded<string, "Email">;

declare function getUser(id: UserId): User;

const id = "abc" as UserId;
getUser(id);            // ok
getUser("abc");         // ❌ TS error — string is not assignable to UserId
```

## Common aliases

```ts
type Nullable<T>        = T | null
type Maybe<T>           = T | null | undefined
type Awaitable<T>       = T | Promise<T>
type NonEmptyArray<T>   = [T, ...T[]]
type GenericObject<T=any> = Record<string, T>
type AlphaNumeric       = string | number
type Primitive          = AlphaNumeric | boolean
```

```ts
function init(input: Awaitable<Config>): Promise<void> { ... }

function first<T>(arr: NonEmptyArray<T>): T {
  return arr[0]; // safe, no `| undefined`
}
```

---

# Recipes

> **Auto-trigger:** code combines two or more `@mongez/reinforcements` imports (e.g. `retry` + `timeout` + `pMap`, `debounce` + `flush`, `walk` + `diff`, `mask` + `pick`, `slugify` + `truncate` + `pipe`); user asks "how do I build resilient HTTP retries / auto-save with cancel / detect object changes / write PII-safe logs / make a tokenization pipeline / break a circular import with lazy"; user wants an end-to-end worked example, not a single-function reference.
> **Skip when:** single-function lookups — load the matching per-namespace skill (objects/strings/numbers/async/functions/lazy/random) for one specific utility; questions about non-@mongez/reinforcements libraries even if the recipe shape looks similar.

Cross-namespace compositions for common real-world tasks. Each recipe is shaped around what you're trying to *do*, not which function it uses.

## Read or write nested fields without losing types

You have a deeply-nested user object and you want to reach into `profile.email` safely — and get back a properly-typed string, not `any`.

```ts
import { get, set, has } from "@mongez/reinforcements";

type User = { id: number; profile: { email: string } };
const u: User = { id: 1, profile: { email: "ada@x.com" } };

get(u, "profile.email");        // typed string
get(u, "profile.email", "n/a"); // typed string, "n/a" fallback
has(u, "profile.email");        // true
set(u, "profile.country", "EG");
```

`get` infers the return type from the path. Compared to `u?.profile?.email`, you also get the default-value branch in one call.

## Fetch many users in parallel, with retries and a deadline

You're hydrating a list of user IDs from an API. Some requests will time out, some will fail transiently, and you don't want to stampede the server with 5,000 simultaneous fetches.

```ts
import { retry, timeout, pMap } from "@mongez/reinforcements";

const safeFetch = (id: string) =>
  retry(
    () => timeout(fetch(`/users/${id}`).then(r => r.json()), 3_000),
    { attempts: 5, delay: 200, backoff: "exponential" },
  );

const users = await pMap(userIds, safeFetch, { concurrency: 5 });
```

`pMap` caps concurrency. `retry` handles transient flakiness. `timeout` ensures no single request hangs the whole batch.

## Autosave a draft while the user types

You're building a text editor that saves to the server. Debounce the save so it fires 500 ms after the last keystroke; flush manually when "Save now" is clicked; cancel pending writes on navigation away.

```ts
import { debounce } from "@mongez/reinforcements";

const autoSave = debounce(payload => api.save(payload), 500, { maxWait: 3_000 });

input.addEventListener("input", e => autoSave(e.target.value));
button.addEventListener("click", () => autoSave.flush());     // "Save now"
window.addEventListener("beforeunload", () => autoSave.cancel());
```

`maxWait: 3_000` guarantees a save fires at least every 3 seconds even if the user types continuously — so no edit can be lost more than 3 s if the tab dies.

## Cache an expensive lookup for one minute

A function that hits the database or an external API, called many times per minute with the same arguments. You want the second call within 60 s to be free.

```ts
import { memoize } from "@mongez/reinforcements";

const lookupUser = memoize(id => db.users.findById(id), { ttl: 60_000 });

await lookupUser("u1");                      // hits DB
await lookupUser("u1");                      // cache (within 60 s)
lookupUser.forget(JSON.stringify(["u1"]));   // invalidate just this key (default key = JSON.stringify(args))
```

`forget(key)` lets you invalidate surgically when a write happens. Without it you'd need a TTL low enough to outpace staleness, which sacrifices the win.

## Audit-log every change between two state snapshots

You're shipping a settings page where every edit must be traced. Diff the old and new objects and emit one audit line per changed field.

```ts
import { walk, diff } from "@mongez/reinforcements";

const changes = diff(prevState, nextState);
for (const key of Object.keys(changes.changed)) {
  audit.log(`${key}: ${changes.changed[key].from} → ${changes.changed[key].to}`);
}
```

`walk` is the read-only sibling — useful for debug-logging the whole tree:

```ts
walk(config, (value, path) => logger.debug(path, value));
```

## Deterministic random data in unit tests

Your test asserts a property of `Random.sample(...)` but the function is non-deterministic. Seed the generator at the top of each test for a stable result.

```ts
import { Random } from "@mongez/reinforcements";

beforeEach(() => Random.seed(42));
afterEach(()  => Random.seed());     // restore non-deterministic mode

test("picks deterministic sample", () => {
  expect(Random.sample([1, 2, 3, 4, 5], 3)).toEqual(/* same every run */);
});
```

Resetting after each test prevents seed bleed if other tests rely on real randomness.

## Break a circular import without restructuring modules

Module A needs B; B needs A. You can't reorder the imports. `lazy` defers the binding capture until first use.

```ts
// a.ts
import { lazy } from "@mongez/reinforcements";
import { B } from "./b";          // b.ts also imports a.ts — circular

const b = lazy(() => B);          // capture binding, defer access

export const A = {
  callB: () => b.resolve().run(),
};
```

The first access calls the factory; subsequent calls return the cached binding. `b.reset()` lets you re-evaluate if the source binding changes (e.g. hot reload).

## Generate a short URL slug from a long title

Blog-post permalinks. The raw title is too long for a URL; you want a clean slug capped at 60 characters, broken at a word boundary.

```ts
import { slugify, truncate, pipe } from "@mongez/reinforcements";

const urlSummary = (title: string) =>
  pipe(title, t => truncate(t, 60, { byWord: true }), t => slugify(t));

urlSummary("How to break circular ES module imports without crying!");
// "how-to-break-circular-es-module-imports-without"
```

`pipe` keeps the order of operations linear — read top-to-bottom instead of nested-function inside-out.

## Log a user object without leaking email or phone

You're shipping an event to your analytics pipeline. PII (email, phone) needs to be masked, and the payload must not carry anything beyond the explicitly-allowed keys.

```ts
import { mask, pick } from "@mongez/reinforcements";

function logUser(user: { id: string; email: string; phone: string }) {
  logger.info(
    pick(
      {
        ...user,
        email: mask(user.email, { start: 2, end: 4 }),
        phone: mask(user.phone, { start: 4, end: 2 }),
      },
      ["id", "email", "phone"],
    ),
  );
}
// Logs e.g.  { id: "u_42", email: "ad****@x.com", phone: "+202********34" }
```

`pick` after the mask is the safety belt — if someone adds a `passwordHash` field to the user shape, it won't accidentally leak because it's not in the allowlist.

## Trace each step of a transform pipeline

You're chasing a bug in a multi-step string transform. Insert a `tap` between steps to log the intermediate value without breaking the pipeline shape.

```ts
import { pipe, tap, trim, toSnakeCase } from "@mongez/reinforcements";

const tokenize = (input: string) =>
  pipe(
    input,
    s => trim(s),
    tap.with(s => log("trimmed:", s)),     // log without consuming
    toSnakeCase,
  );
```

`tap` returns the value untouched after running its side effect — pipeline shape stays linear, debug instrumentation drops in and out at will.

## Layer config sources without duplicating array entries

Boot-time config comes from defaults, then user overrides, then environment overrides. Each layer might contribute to an `allowedHosts` array — you want the union, not the concatenation (which would duplicate).

```ts
import { merge } from "@mongez/reinforcements";

const config = merge(
  defaults,
  userConfig,
  envConfig,
  { arrays: "union" },           // de-dupe across all sources
);
```

`arrays: "union"` builds a `Set` from the concatenated entries — so primitive arrays dedupe cleanly, but **object arrays dedupe by reference**, not by deep equality or a key. If you need shape-based dedup of object arrays, post-process with `unique(arr, "id")` from the arrays skill.

## Render a templated message with nested data

You're sending an email or a notification body. The template uses `{user.name}` placeholders that need to read from a nested object.

```ts
import { template } from "@mongez/reinforcements";

const body = template(
  "Hi {user.name}, you have {count} {kind} waiting.",
  { user: { name: "Ada" }, count: 3, kind: "messages" },
);
// "Hi Ada, you have 3 messages waiting."
```

Dot-notation lookups inside the placeholder map onto the same `get` semantics from the first recipe.

## Generate bracket-notation form names from a schema

You're building an HTML form whose input `name` attributes need to be `user[address][city]` — bracket notation — derived from a nested schema object.

```ts
import { toInputName, flatten } from "@mongez/reinforcements";

const schema = { user: { address: { city: "" }, tags: ["news", "blog"] } };

Object.keys(flatten(schema)).map(toInputName);
// [ "user[address][city]", "user[tags][0]", "user[tags][1]" ]
```

`flatten` produces dot-paths (empty arrays are kept as leaves — populate `tags` with at least one entry if you need indexed names); `toInputName` converts each path to the HTML bracket form. Pair the two when you don't want to hand-author input names alongside the schema.

## Promisify a legacy callback API, with retries

A third-party library uses `(err, result)` callbacks. You want a promise — and because the connection sometimes flakes on first attempt, you want retries on top.

```ts
import { defer, retry } from "@mongez/reinforcements";

const connect = () => {
  const d = defer<Connection>();
  legacy.connect((err, conn) => (err ? d.reject(err) : d.resolve(conn)));
  return d.promise;
};

const conn = await retry(connect, { attempts: 3, delay: 500, backoff: "exponential" });
```

`defer` creates an externally-resolvable promise — useful for any "give me a promise that some other code will settle." `retry` then layers the resilience.

## Search-as-you-type without flooding the backend

A search box that fires an XHR on every keystroke would melt the server. Debounce the async call and let every keystroke await the same in-flight result.

```ts
import { debounceAsync } from "@mongez/reinforcements";

const search = debounceAsync(
  (q: string) => fetch(`/search?q=${q}`).then(r => r.json()),
  250,
);

// User types fast: "a", "ad", "ada"
// Only the final query is fetched; all three awaiters get the same result.
```

Compared to a plain debounce + manual promise plumbing, `debounceAsync` returns a promise that resolves with the *final* call's value — every intermediate caller awaits and receives that same resolution.

## Re-read a lazy value when its source file changes

Config parsed from disk at boot. You want it cached, but you also want a file-watcher to invalidate the cache when the file changes.

```ts
import { lazy } from "@mongez/reinforcements";

const settings = lazy(() => parseConfigFile());

configWatcher.on("change", () => settings.reset());

export const get = (key: string) => settings.resolve()[key];
```

The first `get` parses; subsequent gets read the cached parse; `reset` forces a re-parse on the next access. No global mutable variable, no `if (loaded) …` boilerplate.

## Pick the first defined value (without `||` bugs on `0`)

A port number sourced from CLI input, then env, then default. With `||`, an input port of `0` would silently fall through to the default — a real bug class.

```ts
import { coalesce } from "@mongez/reinforcements";

const port = coalesce(input.port, env.PORT, 3000);
// input.port = 0         → uses 0  (NOT 3000)
// input.port = undefined → falls through to env.PORT
// input.port = null      → falls through to env.PORT
```

`coalesce` distinguishes "no value" from "falsy value" — only `undefined` and `null` count as "no value."

## Strip empty values before posting to an API

A form submission where the user left several optional fields blank. You don't want to send `email: ""` or `prefs: {}` — but you DO want to send `age: 0` (a real value, not absent).

```ts
import { compact } from "@mongez/reinforcements";

const payload = compact({
  name: form.name,
  email: form.email,       // possibly ""        → removed
  phone: form.phone,       // possibly null      → removed
  preferences: form.prefs, // possibly {}        → removed
  age: form.age,           // 0 is valid, kept
});

await api.post("/users", payload);
```

`compact` removes `null`, `undefined`, `""`, `[]`, and `{}` — but keeps numeric `0`, boolean `false`, and any other defined-but-falsy primitives.

## Run four independent fetches in parallel and destructure the results

A page that needs the user, their settings, their home feed, and their unread-count — none depends on the others. Fan out in parallel, destructure when all four resolve.

```ts
import { pProps } from "@mongez/reinforcements";

const { user, settings, home, notifications } = await pProps({
  user:          getUserFromDB(userId),
  settings:      loadSettingsAsync(userId),
  home:          getHomeFeed(userId),
  notifications: getUnreadCount(userId),
});
```

All four requests run in parallel; one rejection rejects the whole thing. Compared to `Promise.all([…])` + array destructuring, `pProps` lets you keep the names visible at the call site instead of relying on positional order.
