---
title: "reduce(): function in Authoring, TypeShade API reference"
description: "reduce, a function in Authoring. Fold a value over a C-style loop: the value-returning spelling of the var acc = init; for (...) { acc = f(acc…"
url: https://typeshade.dev/api/reduce/
language: en
---

# `reduce()`

Function in Authoring

Fold a value over a C-style loop: the value-returning spelling of the var acc = init; for (...) { acc = f(acc, i) } accumulator.

`import { reduce } from 'typeshade/core/ir'`

The signature, the description and the examples come from the compiler's own source at commit af54ddad5.

## Syntax

```ts
function reduce<K extends string, J extends string>(
  init: ReadonlyNode<K>,
  loopInit: ReadonlyNode<J>,
  cond: (i: Node<J>) => ReadonlyNode<'bool'>,
  body: (acc: Node<K>, i: Node<J>) => ReadonlyNode<K>,
  step?: ReadonlyNode<ScalarKey> | number,
): Node<K>
```

## Parameters

**`init` `ReadonlyNode<K>`**

the accumulator’s initial value, which also fixes its type.

**`loopInit` `ReadonlyNode<J>`**

the counter’s initial value.

**`cond` `(i: Node<J>) => ReadonlyNode<'bool'>`**

the continue test, receiving the counter.

**`body` `(acc: Node<K>, i: Node<J>) => ReadonlyNode<K>`**

receives the accumulator and the counter, and returns the next accumulator.

**`step` optional `ReadonlyNode<ScalarKey> | number`**

the per-iteration increment. Defaults to `+1`.

## Return value

`Node<K>`

a node reading the accumulator after the loop.

## Description

The body returns the next accumulator value, so the call site declares no `Var` and writes no `assign`; `reduce` materialises the variable, the loop and the assignment internally, and the emitted statements are the same as the hand-written form. Returns the accumulator node for use after the loop.

## Examples

### Example

```ts
import { reduce, toF32, f32, u32 } from 'typeshade/core/ir'

const sum = reduce(f32(0), u32(0), (i) => i.lt(u32(8)), (acc, i) => acc.add(toF32(i)))
```

## In the guide

- [Control flow](https://typeshade.dev/guide/internals/control-flow/)

## See also

- [`Loop`](https://typeshade.dev/api/loop/)
- [`when`](https://typeshade.dev/api/when/)

## Source

[`src/core/ir/builder.ts`, line 1660](https://github.com/typeshade/typeshade/blob/af54ddad5/src/core/ir/builder.ts#L1660), at commit af54ddad5
