# Customise stored data

Give patrun a function that changes each pattern as it is added, and that changes what find gives back.

Use this when every pattern needs the same change, or `find` should give back something other than the stored data. Give `patrun` a function, the customiser. `add` calls it with each pattern and its data, and it can change the pattern, or return a function that `find` calls on the data.

This customiser adds a property to every pattern, so a query must have it too:

```js
const patrun = require('patrun')

const alwaysAddFoo = patrun(function (pattern) {
  pattern.foo = true
})

alwaysAddFoo.add({ a: 1 }, 'bar')
alwaysAddFoo.find({ a: 1 }) // → null
alwaysAddFoo.find({ a: 1, foo: true }) // → 'bar'
```

This one returns a function that changes what `find` gives back:

```js
const patrun = require('patrun')

const upperify = patrun(function (pattern) {
  return function (query, data) {
    return ('' + data).toUpperCase()
  }
})

upperify.add({ a: 1 }, 'bar')
upperify.find({ a: 1 }) // → 'BAR'
```

A customiser can also return an object with a `find` function and a `remove` function. This one keeps every piece of data added for a pattern, and `remove` takes off the last:

```js
const patrun = require('patrun')

const many = patrun(function (pattern, data) {
  const items = this.findExact(pattern) || []
  items.push(data)

  return {
    find: (query, data) => (items.length ? items : null),
    remove: (pattern, data) => {
      items.pop()
      return items.length === 0
    },
  }
})

many.add({ a: 1 }, 'A')
many.add({ a: 1 }, 'B')
many.find({ a: 1 }) // → ['A', 'B']
many.remove({ a: 1 })
many.find({ a: 1 }) // → ['A']
```

`remove` clears the pattern only when the customiser's `remove` returns a true value.

## What to watch for

The patterns alone decide which pattern matches. `find` chooses the most specific pattern as always, and only then calls that pattern's function. Whatever it returns is the answer, `null` included: `find` does not go on to another pattern. `collect`, `get`, and `list` give the data as it was stored.

To use a customiser with options, set the options on the function itself: `custom.order = ['srv']`. The Go port has no customiser.
