getPredicateCodec
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 Parameter | Default type | Description |
|---|---|---|
TFrom | any | The type of the value to encode. |
TTo | TFrom | The type of the value to decode. |
TIfTrue extends Codec<TFrom, TTo> | Codec<TFrom, TTo> | - |
TIfFalse extends Codec<TFrom, TTo> | Codec<TFrom, TTo> | - |
Parameters
| Parameter | Type | Description |
|---|---|---|
encodePredicate | (value) => boolean | A function that returns true or false for a given value. |
decodePredicate | (value) => boolean | A function that returns true or false for a given byte array. |
ifTrue | TIfTrue | The codec to use when the respective predicate returns true. |
ifFalse | SameType<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> & TIfFalse | The 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.