Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript equivalent to Guava's Preconditions?

In Java, I check my preconditions using Google Guava:

public Port getPublishedPort(Port port) {
    checkArgument(port.isPublishedPort(), "Given port %s is not a published port.", port);

Is there an equivalent to this in JavaScript?

like image 508
Frederik Avatar asked Sep 13 '13 11:09

Frederik


People also ask

What is preconditions checkArgument?

The method checkArgument of the Preconditions class ensures the truthfulness of the parameters passed to the calling method. This method accepts a boolean condition and throws an IllegalArgumentException when the condition is false.

What are preconditions in Java?

A precondition is a condition that must be true for your method code to work, for example the assumption that the parameters have values and are not null. The methods could check for these preconditions, but they do not have to. The precondition is what the method expects in order to do its job properly.


2 Answers

The Node.js Preconditions Library is billed as having a Guava-like API for precondition checks.

Support for Guava like Precondition error checking in Node.js

new InstanceValidator(port).checkArgument(
        "publishedPort", "Given port %s is not a published port.", [port]);
like image 183
CBP Avatar answered Oct 07 '22 21:10

CBP


I authored Requirements.js. Usage looks like this:

import {requireThat} from "@cowwoc/requirements/es6/node/DefaultRequirements.js"

class Player
{
  constructor(name, age)
  {
    requireThat(name, "name").isNotNull().asString().length().isBetween(1, 30);
    requireThat(age, "age").asNumber().isBetween(18, 30);
  }
}

The primary focus is on the readability. Here is what the output looks like:

RangeError: age must be in range [18, 30).
Actual: 15

I welcome your feedback.

like image 29
Gili Avatar answered Oct 07 '22 21:10

Gili