Skip to content

RonaldZav/result-pattern

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@ronaldzav/result-pattern

📁 Alternative to Try/catch for JavaScript

Installation

npm install @ronaldzav/result-pattern

If you are using yarn:

yarn add @ronaldzav/result-pattern

You can use the latest version of result-pattern by adding it as a dependency in your package.json file:

    "dependencies": {
      "@ronaldzav/result-pattern": "github:ronaldzav/result-pattern"
    }

Usage

let { Result } = require('@ronaldzav/result-pattern');

function divide(a, b) {
    if (b == 0) {
      return Result.Failure("Division by zero");
    }
    return Result.Success(a / b);
  }

  if (divide(10, 2).isSuccess()) {
    console.log("Success:", result1.getValue());

  } else {
    console.log("Failure:", result1.getError());

  }

API

Result

The Result class represents a result of a computation that may either be successful or failed.

Result.Success(value)

Returns a successful result with the given value.

Result.Failure(error)

Returns a failed result with the given error.

isSuccess()

Returns true if the result is successful, false otherwise.

isFailure()

Returns true if the result is failed, false otherwise.

getValue()

Returns the value of the successful result, or throws an error if the result is failed.

getError()

Returns the error of the failed result, or throws an error if the result is successful.

Speed Comparison

Speed Test Comparison Image

License

Copyright 2024 Ronald Zavaleta | Apache-2.0 License | Support

About

Alternative to Try/catch for JavaScript

Topics

Resources

License

Stars

Watchers

Forks