throw-return

0.0.1 • Public • Published

throw-return

Return using throw

npm install throw-return

npm Build Status Greenkeeper badge

Throw errors to communicate a return value.

Warning: Evaluate your use cases before using this library. Using error handling to short-circuit functions is slower and more obscure than returning. This library should be used as part of a larger abstraction. Unless that abstraction provides more benefits in itself, go with plain return.

Documentation

throwReturnError

throwReturnError(value: any[, message: String])

Throw an error communicating value as the return value. Optionally give the error a message.

handleReturnError

handleReturnError(func: Function): any

Invoke func and, if a throw-return error is thrown, return the communicated value. If a promise is returned rejecting a throw-error error, the communicated value is resolved.

Example

We have found if (!y) return x too tiresome to write. Let's build an assert(y, x) to save some keystrokes.

Instead of this:

function example () {
  if (!condition1) {
    return value1
  }
  if (!condition2) {
    return value2
  }
  return value3
}

We can do:

function example () {
  assert(condition1, value1)
  assert(condition2, value2)
  return value3
}

If you define assert and control all calls to example:

function assert (condition, value) {
  if (!condition) {
    throwReturnError(value)
  }
}

function run (func) {
  return handleReturnError(func)
}

const value = run(example)

Readme

Keywords

Package Sidebar

Install

npm i throw-return

Weekly Downloads

0

Version

0.0.1

License

MIT

Unpacked Size

7.52 kB

Total Files

7

Last publish

Collaborators

  • andrejewski