Logo

dev-resources.site

for different kinds of informations.

Using match with Option in Effect

Published at
7/3/2024
Categories
effect
javascript
typescript
functional
Author
almaclaine
Author
10 person written this
almaclaine
open
Using match with Option in Effect

The match function in Effect-TS is a versatile utility that allows developers to handle cases of Option values (Some and None) in a functional and expressive manner. It provides a way to define actions or computations that should occur based on the presence or absence of a value within an Option. By using match, you can succinctly specify different behaviors for Some and None without the need for explicit conditional checks, thus making your code cleaner and easier to understand. This function enhances code readability and maintainability by encapsulating conditional logic in a declarative style.

Example 1

Match an Option and provide different behaviors for Some and None using O.match.

This example demonstrates returning different messages based on whether the Option contains a value or not.

import { Option as O, pipe } from 'effect';

function match_ex01() {
  const some = O.some(1);
  const none = O.none();

  const handleOption = O.match({
    onNone: () => 'Option is None',
    onSome: (value) => `Option contains: ${value}`,
  });

  console.log(handleOption(some)); // Output: Option contains: 1
  console.log(handleOption(none)); // Output: Option is None
}
Enter fullscreen mode Exit fullscreen mode

Example 2

Match an Option and perform different side effects based on whether it is Some or None.

This example demonstrates logging messages based on the presence of a value.

function match_ex02() {
  const some = O.some(1);
  const none = O.none();

  pipe(
    some,
    O.match({
      onNone: () => console.log('Option is None'), // Log a message if the Option is None
      onSome: (value) => console.log(`Option contains: ${value}`), // Log the value if the Option is Some
    })
  ); // Output: Option contains: 1

  pipe(
    none,
    O.match({
      onNone: () => console.log('Option is None'), // Log a message if the Option is None
      onSome: (value) => console.log(`Option contains: ${value}`), // Log the value if the Option is Some
    })
  ); // Output: Option is None
}
Enter fullscreen mode Exit fullscreen mode

Example 3

Match an Option and return a default value if it is None using O.match.
This example demonstrates providing a default value for a None case.

function match_ex03() {
  const some = O.some(1);
  const none = O.none();

  const getValueOrDefault = (
    option: O.Option<number>,
    defaultValue: number
  ): number =>
    pipe(
      option,
      O.match({
        onNone: () => defaultValue, // Return the default value if the Option is None
        onSome: (value) => value, // Return the contained value if the Option is Some
      })
    );

  console.log(getValueOrDefault(some, 0)); // Output: 1 (since some contains 1)
  console.log(getValueOrDefault(none, 0)); // Output: 0 (since none is None)
}
Enter fullscreen mode Exit fullscreen mode

Example 4

Match an Option and perform computations based on the contained value using O.match.

This example demonstrates different computations based on the presence of a value.

function match_ex04() {
  const some = O.some(2);
  const none = O.none();

  const compute = O.match({
    onNone: () => 0, // Return 0 if the Option is None
    onSome: (value: number) => value * value, // Compute the square of the value if the Option is Some
  });

  console.log(compute(some)); // Output: 4 (since some contains 2 and 2*2 = 4)
  console.log(compute(none)); // Output: 0 (since none is None)
}
Enter fullscreen mode Exit fullscreen mode

Example 5

Match an Option with more complex types and return a message based on the presence of a value.

This example demonstrates matching an Option containing an object.

function match_ex05() {
  const some = O.some({ key: 'value' });
  const none = O.none();

  const handleComplexOption = O.match<string, { key: string }>({
    onNone: () => 'No data available', // Return a message if the Option is None
    onSome: (obj) => `Data: ${obj.key}`, // Return the key of the object if the Option is Some
  });

  console.log(handleComplexOption(some)); // Output: Data: value
  console.log(handleComplexOption(none)); // Output: No data available
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, the match function is an essential tool in the Effect-TS library that simplifies handling optional values with the Option type. By providing clear, type-safe ways to distinguish between Some and None, match helps avoid common errors associated with null checks and enhances the functional programming capabilities in TypeScript. As demonstrated through various examples, using match not only makes the code more robust but also significantly improves its readability and expressiveness. Adopting this pattern can lead to cleaner, more maintainable codebases where optional values are a common occurrence.

effect Article's
30 articles in total
Favicon
Wrapping up 2024
Favicon
This Week in Effect - 2024-12-27
Favicon
Effect 3.12 (Release)
Favicon
Effect 3.11 (Release)
Favicon
Cause & Effect Podcast #1
Favicon
Mapping Operations in Effect-TS Optionals
Favicon
Using do Notation in Effect-TS Optionals
Favicon
Exploring Option Getters in Effect-TS
Favicon
Exploring Option Conversions in Effect-TS
Favicon
Using match with Option in Effect
Favicon
Using match with Option in Effect
Favicon
Effect in React
Favicon
Understanding Type Guards in Effect-TS: Ensuring Safe Option Handling
Favicon
Exploring Option Constructors in Effect-TS
Favicon
Introduction to Options in Effect
Favicon
Effects in Ember
Favicon
How we migrated our codebase from fp-ts to Effect
Favicon
Synthetic Turf Benefits: Cost-Effective Solutions for Public Spaces
Favicon
The Effect Tax
Favicon
Effect 3.0
Favicon
Effect Days conference on Feb 23, 2024 in Vienna
Favicon
Link: OCAML 5 is Out + Effects Tutorial
Favicon
How To Fade In And Out In Premiere Pro
Favicon
React - Don't update parent state in the rendering phase of the child
Favicon
Encoding HKTs in TypeScript (Once Again)
Favicon
Developing A Wrapper Around Node.Js FS
Favicon
Contentlayer & Effect — Architectural Patterns And Decisions.
Favicon
JavaScript photo efffect fun project
Favicon
Matrix (and perlish) background effect in Javascript :)
Favicon
Social Media Buttons with HTML and CSS ( blur effect ).

Featured ones: