1.0.0 • Published 9 years ago
optionaljs v1.0.0
OptionalJS provides a functional Optional, for JavaScript.
About
The Optional is loosely based upon the Java8 Optional class.
Like the Java8 version, it is not recommended to use the Optional like this:
const myopt = Optional.of("myvalue");
if(myopt.hasValue()) {
console.log("the optional has the value ", myopt.getDirect());
}Although the above is perfectly legal, it is recommended to use one of the many alternatives described below.
Howto
using optionaljs
Add optionaljs as a dependency to package.json:
yarn add optionaljs or npm install optionaljs
Use optional in your code:
// ecmascript 2015 / ES6
import Optional from "optionaljs";
// pre ecmascript 2015 / ES6
var Optional = require("optionaljs");Creating the Optional
Creates an Optional with a value:
const myopt = Optional.of("myvalue");Creates an empty Optional:
const myopt = Optional.empty();Testing for a value
please try to avoid doing this:
if(myopt.hasValue()) {
// ...
}Getting the value: the wrong way
please try to avoid doing this:
const value = myopt.getDirect();Getting the value: the right way
Using a Promise
myopt.get()
.then(value => console.log("the value is", value))
.catch(() => console.log("the Optional does not have a value"));Using a function a argument
myopt.ifPresent(value => console.log("the value is", value));With an alternative value
const myopt = Optional.of("fizzbuzz");
const value = myopt.orElse("foobar"); // value = "fizzbuzz" const myopt = Optional.empty();
const value = myopt.orElse("foobar"); // value = "foobar" Returning the value of another function if nor present
const myopt = Optional.of("fizzbuzz");
const value = myopt.orElseGet(() => "foobar"); // value = "fizzbuzz" const myopt = Optional.empty();
const value = myopt.orElseGet(() => "foobar"); // value = "foobar" JavaScript ....
... and since functions are first-class citizens in JavaScript, one can get really crazy ;-)
1.0.0
9 years ago