File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ export declare class Either < L = unknown , R = unknown > {
2+ constructor ( params : { left ?: L | null ; right ?: R | null } ) ;
3+
4+ static left < L > ( value : L ) : Either < L , null > ;
5+
6+ static right < R > ( value : R ) : Either < null , R > ;
7+
8+ get left ( ) : L | null ;
9+
10+ get right ( ) : R | null ;
11+
12+ isLeft ( ) : boolean ;
13+
14+ isRight ( ) : boolean ;
15+
16+ map < U > ( fn : ( value : R ) => U ) : Either < L , U > ;
17+
18+ match < T > (
19+ leftFn : ( left : L ) => T ,
20+ rightFn : ( right : R ) => T
21+ ) : T ;
22+ }
Original file line number Diff line number Diff line change 1+ 'use strict' ;
2+
3+ class Either {
4+ #left = null ;
5+ #right = null ;
6+
7+ constructor ( { left = null , right = null } ) {
8+ this . #left = left ;
9+ this . #right = right ;
10+ }
11+
12+ static left ( value ) {
13+ return new Either ( { left : value , right : null } ) ;
14+ }
15+
16+ static right ( value ) {
17+ return new Either ( { left : null , right : value } ) ;
18+ }
19+
20+ get left ( ) {
21+ return this . #left;
22+ }
23+
24+ get right ( ) {
25+ return this . #right;
26+ }
27+
28+ isLeft ( ) {
29+ return this . #left !== null ;
30+ }
31+
32+ isRight ( ) {
33+ return this . #right !== null ;
34+ }
35+
36+ map ( fn ) {
37+ if ( this . #right === null ) return this ;
38+ return Either . right ( fn ( this . #right) ) ;
39+ }
40+
41+ match ( leftFn , rightFn ) {
42+ const isRight = this . #right !== null ;
43+ return isRight ? rightFn ( this . #right) : leftFn ( this . #left) ;
44+ }
45+ }
46+
47+ // Usage
48+
49+ const success = Either . right ( 42 ) ;
50+ const failure = Either . left ( 500 ) ;
51+
52+ const doubled = success . map ( ( x ) => x * 2 ) ;
53+ console . log ( { doubled : doubled . right } ) ;
54+
55+ const result = failure . match (
56+ ( error ) => `Failure: ${ error } ` ,
57+ ( value ) => `Success: ${ value } ` ,
58+ ) ;
59+
60+ console . log ( { result } ) ;
You can’t perform that action at this time.
0 commit comments