tapDecoder

function tapDecoder<TDecoder>(decoder, tap): TDecoder;

Observes the decoded value of a decoder after it is decoded, without modifying it.

This function takes an existing decoder and returns a new decoder of the exact same type that calls the provided tap function with each decoded value before returning it. The value is passed through unchanged, making this useful for adding validation guards, logging, or other read-only side effects on the decoded value.

If the tap function throws, the decoding is aborted and the error propagates to the caller.

Type Parameters

Type ParameterDescription
TDecoder extends AnyDecoderThe type of the decoder being tapped. The returned decoder has the same type.

Parameters

ParameterTypeDescription
decoderTDecoderThe decoder whose decoded value should be observed.
tap(value) => voidA function called with each decoded value. It may throw to abort decoding.

Returns

TDecoder

A new decoder of the same type that observes its decoded value.

Throws

Whatever error the tap function throws, aborting the decoding.

Example

Guarding the decoded value of a u8 decoder.

const decoder = tapDecoder(getU8Decoder(), value => {
    if (value === 0) throw new Error('Value must not be zero');
});
decoder.decode(new Uint8Array([42])); // 42
decoder.decode(new Uint8Array([0])); // Throws 'Value must not be zero'

Remarks

To observe the raw bytes before decoding instead of the decoded value, use tapDecoderBytes.

See

On this page