getPatternMatchEncoder

function getPatternMatchEncoder<TPatterns>(
    patterns,
): GetUnionEncoderType<GetPatternMatchEncoders<TPatterns>>;

Returns an encoder that selects which variant encoder to use based on pattern matching.

This encoder evaluates the value against a series of predicate functions in order, and uses the first matching encoder to encode the value.

Type Parameters

Type Parameter
TPatterns extends readonly ( | readonly [(value) => value is any, Encoder<any>] | readonly [(value) => boolean, Encoder<any>])[]

Parameters

ParameterTypeDescription
patternsTPatterns & readonly PatternMatchEncoderEntry<GetEncoderTypeFromVariants<GetPatternMatchEncoders<TPatterns>>, GetEncoderTypeFromVariants<GetPatternMatchEncoders<TPatterns>>>[]An array of [predicate, encoder] pairs. Predicates are tested in order and the first matching encoder is used to encode the value. Note that predicates can be either type predicates that narrow the type of the value, or boolean predicates. If using type predicates, the encoder can be for the narrowed type.

Returns

GetUnionEncoderType<GetPatternMatchEncoders<TPatterns>>

An encoder that selects the appropriate variant based on the matched pattern.

Throws

Throws a SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE error if the value does not match any of the specified patterns.

Example

Encoding values using pattern matching.

const encoder = getPatternMatchEncoder([
  [(n: number) => n < 256, getU8Encoder()],
  [(n: number) => n < 2 ** 16, getU16Encoder()],
  [(n: number) => n < 2 ** 32, getU32Encoder()]
]);
 
encoder.encode(42);
// 0x2a
//  └── Small number encoded as u8
 
encoder.encode(1000);
// 0xe803
//   └── Medium number encoded as u16
 
encoder.encode(100_000);
// 0xa0860100
//   └── Large number encoded as u32
 
ender.encode(2 ** 32 + 1);
// Throws an error because the value does not match any pattern

See

getPatternMatchCodec

On this page