JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 361033
  • Score
    100M100P100Q158920F
  • License MIT

Java 8 Optionals for JS

Package Exports

  • optional-js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (optional-js) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Optional.js

A container object that wraps possible undefined values in JavaScript - inspired by Java 8 Optionals

Optional.ofNullable(promptForUserName)
        .map(getUserId)
        .filter(verify)
        .ifPresent(login);

Features

  • Full Java 8 Optional API is supported
  • Runs in browser and node environments
  • Lightweight and dependency-free (<1.0 KB minified, gzipped)

Installation

Download the latest release from GitHub or from NPM

via npm:

$ npm install optional-js

then just require in node:

var Optional = require('optional-js');
var emptyOptional = Optional.empty();

alternatively, use the browser compatible build in the ./dist directory of the npm package

Not using a module loader? Include the script, and the browser global Optional will be added to window.

Usage

Full docs - Java 8 Optionals

JS Example:

// "login.js"

var Optional = require('optional-js');

// Here, we grab a potentially undefined value
var userName = process.argv[2];

// Now we wrap it in an Optional, and use the delicious, functional, sugary sweet API
Optional.ofNullable(userName)
        .map(getUserId)
        .filter(verify)
        .ifPresent(login);

function getUserId(userName) {
    return userName === 'root' ? 1234 : 0;
}

function verify(userId) {
    return userId === 1234;
}

function login(userId) {
    console.log('Logging in as : ' + userId);
}

Then, from the terminal...

$ node login root
"Logging in as : 1234"

Building

download:

git clone git@github.com:JasonStorey/Optional.js.git

enter the directory, and install dependencies:

cd Optional.js && npm install

build:

npm run build

run the tests:

npm test

Contributing

Found a bug or missing feature? Please open an issue!

Send your feedback. Send your pull requests. All contributions are appreciated!

Copyright and license

Created and copyright (c) 2014-2015 by Jason A. Storey

Optional.js may be freely distributed under the MIT license.