getPredicateDecoder

function getPredicateDecoder<TTo, TIfTrue, TIfFalse>(
    predicate,
    ifTrue,
    ifFalse,
): GetUnionDecoderType<readonly [TIfTrue, TIfFalse]>;

Returns a decoder that selects between two decoders based on a predicate.

This decoder uses a boolean predicate function on the raw bytes to determine which of two decoders to use. If the predicate returns true, the ifTrue decoder is used; otherwise, the ifFalse decoder is used.

Type Parameters

Type ParameterDefault typeDescription
TToanyThe type of the value to decode.
TIfTrue extends Decoder<TTo>Decoder<TTo>-
TIfFalse extends Decoder<TTo>Decoder<TTo>-

Parameters

ParameterTypeDescription
predicate(value) => booleanA function that returns true or false for a given byte array.
ifTrueTIfTrueThe decoder to use when the predicate returns true.
ifFalseSameType<TIfTrue extends Decoder<TFrom> ? TFrom : never, TIfFalse extends Decoder<TFrom> ? TFrom : never> & TIfFalseThe decoder to use when the predicate returns false.

Returns

GetUnionDecoderType<readonly [TIfTrue, TIfFalse]>

A Decoder based on the provided decoders.

Example

Decoding small and large numbers based on byte length.

const decoder = getPredicateDecoder(
  bytes => bytes.length === 1,
  getU8Decoder(),
  getU32Decoder()
);
 
decoder.decode(new Uint8Array([0x2a]));
// 42 (decoded as u8)
 
decoder.decode(new Uint8Array([0xe8, 0x03, 0x00, 0x00]));
// 1000 (decoded as u32)

See

getPredicateCodec

On this page