UNPKG

@rustable/enum

Version:

Rust-inspired pattern matching and type-safe error handling for TypeScript. Includes Option<T> for null-safety and Result<T, E> for error handling, with comprehensive pattern matching support

96 lines (92 loc) 2.54 kB
'use strict'; var _enum = require('./enum.js'); var option = require('./option.js'); "use strict"; class ControlFlow extends _enum.Enum { static Continue(value) { return new ControlFlow("Continue", value); } static Break(value) { return new ControlFlow("Break", value); } /** * Pattern matches on the ControlFlow * @param patterns Object containing handlers for Continue and Break cases * @returns Result of the matched handler * * @example * ```typescript * const flow = Continue(42); * const result = flow.match({ * Continue: (val) => `Continuing with ${val}`, * Break: (val) => `Breaking with ${val}`, * }); * ``` */ match(patterns) { return super.match(patterns); } /** * Returns true if this is a Break variant */ isBreak() { return this.is("Break"); } /** * Returns true if this is a Continue variant */ isContinue() { return this.is("Continue"); } /** * Returns the Break value if this is Break, throws otherwise * @throws Error if this is not a Break variant */ breakValue() { return this.isBreak() ? option.Some(super.unwrap()) : option.None; } /** * Returns the Continue value if this is Continue, throws otherwise * @throws Error if this is not a Continue variant */ continueValue() { return this.isContinue() ? option.Some(super.unwrap()) : option.None; } /** * Maps the Break value using the provided function * @param fn Function to transform the Break value * @returns New ControlFlow with mapped Break value * * @example * ```typescript * const flow = Break(42); * const mapped = flow.mapBreak(x => x.toString()); // Break("42") * ``` */ mapBreak(fn) { return this.isBreak() ? ControlFlow.Break(fn(super.unwrap())) : ControlFlow.Continue(super.unwrap()); } /** * Maps the Continue value using the provided function * @param fn Function to transform the Continue value * @returns New ControlFlow with mapped Continue value * * @example * ```typescript * const flow = Continue(42); * const mapped = flow.mapContinue(x => x.toString()); // Continue("42") * ``` */ mapContinue(fn) { return this.isContinue() ? ControlFlow.Continue(fn(super.unwrap())) : ControlFlow.Break(super.unwrap()); } } function Continue(value) { return ControlFlow.Continue(value); } function Break(value) { return ControlFlow.Break(value); } exports.Break = Break; exports.Continue = Continue; exports.ControlFlow = ControlFlow;