# Computed

Source: https://signy.dev/documentation/1/reactivity/computed/

A cached value derived from other signals.

## Create a computed

```js
const count = new Signal(2);
const double = new Computed(() => count.value * 2);
const label = computed(() => `${count.value} items`);

double.value; // 4
```

A computed reads like a signal but you cannot write it. It recomputes lazily: only when it is read after a signal it depends on changed.

Like a signal, `double.peek()` reads the current value without tracking it.

## Example

```js
const { Component, Signal, Computed, application, html } = Signy;

class Order extends Component {
  quantity = new Signal(1);
  price = 12.5;
  total = new Computed(() => (this.quantity.value * this.price).toFixed(2));

  render() {
    return html`
      <label>
        Quantity
        <input type="number" min="1" value="1"
          onInput=${(e) => (this.quantity.value = Number(e.currentTarget.value) || 0)} />
      </label>
      <p>Total: ${() => this.total.value} EUR</p>
    `;
  }
}

application(Order).mount("#computed-total");
```

## Chains

Computed values can read other computed values. Each one recomputes at most once per change, however many readers it has.

```js
const items = new Signal([3, 8, 1]);
const sorted = computed(() => [...items.value].sort((a, b) => a - b));
const smallest = computed(() => sorted.value[0]);
```
