getPredicateCodec

function getPredicateCodec<TFrom, TTo, TIfTrue, TIfFalse>(
    encodePredicate,
    decodePredicate,
    ifTrue,
    ifFalse,
): GetUnionCodecType<readonly [TIfTrue, TIfFalse]>;

Returns a codec that selects between two codecs based on predicates.

This codec uses boolean predicate functions to determine which of two codecs to use for encoding and decoding. If the encoding predicate returns true for a value, the ifTrue codec is used to encode it; otherwise ifFalse. Similarly, if the decoding predicate returns true for the bytes, the ifTrue codec is used to decode them.

Type Parameters

Type ParameterDefault typeDescription
TFromanyThe type of the value to encode.
TToTFromThe type of the value to decode.
TIfTrue extends Codec<TFrom, TTo>Codec<TFrom, TTo>-
TIfFalse extends Codec<TFrom, TTo>Codec<TFrom, TTo>-

Parameters

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

Returns

GetUnionCodecType<readonly [TIfTrue, TIfFalse]>

A Codec based on the provided codecs.

Example

Encoding and decoding small and large numbers differently.

const codec = getPredicateCodec(
  (n: number) => n < 256,
  bytes => bytes.length === 1,
  getU8Codec(),
  getU32Codec()
);
 
const smallBytes = codec.encode(42);
// 0x2a (encoded as u8)
 
const largeBytes = codec.encode(1000);
// 0xe8030000 (encoded as u32)
 
codec.decode(smallBytes); // 42
codec.decode(largeBytes); // 1000

See

On this page