# customCache

> **customCache**<`K`, `V`>(`options`): [`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>

Defined in: [packages/cache/src/custom-cache.ts:92](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/custom-cache.ts#L92)

Create a [Cache](/reference/knotkit/cache/interfaces/cache/) that evicts in the order a caller-supplied `CacheEvictionPolicy` chooses.

Choose it when none of the built-in policies fits: a cost-aware, priority, or domain-ordered eviction. The options are those of every built-in factory plus `policy`, which is called once, after the options are validated, with the validated capacity. The cache keeps owning entries, weights, expiry, and iteration; the policy sees keys only, never the cache’s storage.

The cache calls the policy synchronously:

* `added(key)` after `set` stores a key it did not hold;
* `used(key)` after `get` finds the key, or after `set` replaces it;
* `chooseVictim(context)` each time `set` needs room, before anything is removed for that eviction, then `deleted(victim)`;
* `deleted(key)` whenever a key leaves for any reason but `clear`: `delete`, eviction, or an expired entry that a read, `set`, or `deleteExpired` drops;
* `clear()`, when present, on `clear`.

`peek` and `has` never report a use; they report `deleted` only when they drop an entry they find expired. An expired victim is dropped without being returned from `set`, as with the built-in policies. A custom cache keeps no ghosts of evicted keys.

The answer of `chooseVictim` is checked before anything is removed for it: a key the cache does not hold, or the key being set, throws `INVALID_VICTIM`. While any callback runs, a call into the same cache’s `get`, `peek`, `has`, `set`, `delete`, `deleteExpired`, `clear`, `keys`, `values`, `entries`, or a step of one of their walks throws `REENTRANT_POLICY`; a step that throws it ends that walk.

An error a callback throws propagates. What it leaves behind:

* `chooseVictim` throwing, or answering an invalid key, leaves the cache unchanged when it happens on the first eviction of a `set`. When one `set` evicts several entries for a heavy write, the evictions already made stand, and were reported to `deleted`; the new value is not stored. Either way, an expired entry of the key being set may already have been dropped, which no read could have told apart.
* `deleted` throwing leaves the key in the cache: the call that was removing it stops before it does.
* `added` and `used` run after the write or read they report, so when either throws, the value is already stored and counted.
* `clear` throwing leaves every entry in place.

In each case the policy’s own bookkeeping is whatever the throwing callback left, and the cache stays usable.

Costs are those of the policy plus a constant per operation: one wrapper call and one flag check on every member, a `try`/`finally` around every callback, and one extra key lookup per eviction to validate the victim. Expect it to run slower than the built-in policies, which keep their order in the slot store’s typed arrays rather than in caller objects.

## Type Parameters

### K

`K`

### V

`V`

## Parameters

### options

[`CustomCacheOptions`](/reference/knotkit/cache/interfaces/customcacheoptions/)<`K`, `V`>

## Returns

[`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>

## Throws

At construction, with `INVALID_CAPACITY`, `MISSING_CLOCK`, or `INVALID_TIME_TO_LIVE` as every factory does. From `set`, `INVALID_VICTIM` as described above, besides the codes every [Cache](/reference/knotkit/cache/interfaces/cache/) member throws; from every member but `kind`, `size`, and `totalWeight`, `REENTRANT_POLICY` when called from inside a callback.

## Example

```ts
// Evict the oldest key first, ignoring reads: first-in, first-out.
function firstInFirstOut<K>(): CacheEvictionPolicy<K> {
  const order = new Set<K>()
  return {
    added: (key) => void order.add(key),
    used: () => {},
    deleted: (key) => void order.delete(key),
    chooseVictim: ({ protectedKey }) => [...order].find((key) => key !== protectedKey)!,
    clear: () => order.clear(),
  }
}

const cache = customCache<string, number>({ capacity: 2, policy: firstInFirstOut })
cache.set('a', 1)
cache.set('b', 2)
cache.get('a')
cache.set('c', 3) // [{ key: 'a', value: 1 }]
```
