@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
92 lines (89 loc) • 2.45 kB
JavaScript
import { Enum } from './enum.mjs';
import { Some, None } from './option.mjs';
;
class ControlFlow extends 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() ? Some(super.unwrap()) : None;
}
/**
* Returns the Continue value if this is Continue, throws otherwise
* @throws Error if this is not a Continue variant
*/
continueValue() {
return this.isContinue() ? Some(super.unwrap()) : 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);
}
export { Break, Continue, ControlFlow };