This implementation represents a type that can hold either a value of type L
(Left) or a value of type R
(Right). It is a common pattern in functional programming to handle computations that can result in two different types of outcomes, such as success or failure.
To create an Either
instance, you can use the static methods left
and right
:
const { Either } = require('./either');
// Create a Left value
const leftValue = Either.left('Error occurred');
// Create a Right value
const rightValue = Either.right(42);
if (leftValue.isLeft) {
console.log('This is a Left value');
}
if (rightValue.isRight) {
console.log('This is a Right value');
}
const left = leftValue.left(); // 'Error occurred'
const right = rightValue.right(); // 42