Decoding
Decode bytes back to typed values.
Roundtrip with .andThen()
Chain encoding and decoding operations:
// examples/core/encode-roundtrip.ts
// Demonstrates: Chaining encode and decode with .andThen()
import { encode, decode, String_ } from "@grounds/core";
// Chain encode -> decode using .andThen()
// If encode fails, decode is skipped and the error propagates
const roundtrip = encode(String_("hello world")).andThen((bytes) => decode(bytes));
// Handle the final result
roundtrip.match(
(value) => {
console.log("Roundtrip successful!");
console.log("Original: hello world");
console.log("Decoded:", value);
},
(err) => {
console.error("Roundtrip failed:", err.message);
},
);
The .andThen() method chains fallible operations. If encoding fails, decoding is skipped and the error propagates.
Decoding Standalone
You can also decode bytes directly:
import { decode } from "@grounds/core";
// Decode some bytes
decode(bytes).match(
(value) => console.log("Decoded:", value),
(err) => console.error("Failed:", err.message),
);
Type Information
Decoded values include their type code:
decode(bytes).match(
(value) => {
console.log("Type:", value.type); // e.g., TypeCode.String
console.log("Value:", value.value); // e.g., "hello"
},
(err) => console.error(err.message),
);
Next Steps
Learn about Error Handling for robust error management.