getify / monio

The most powerful IO monad implementation in JS, possibly in any language!
http://monio.run
MIT License
1.06k stars 58 forks source link
either fp functional-programming io javascript js maybe monad monads observable

Monio

Build Status npm Module Coverage Status Modules License

Monio (mō'ne-yo) provides an async-capable IO Monad (including "do" style) for JS, with several helpful companion monads (like Maybe and Either) thrown in.

Monio's IO/IOx is the most powerful IO monad implementation in JS, possibly in any language!

Note: This is obviously a marketing claim, not a provable mathematical/scientific assertion. Nevertheless, I believe it's true!

Just("Welcome, Monads")
.concat(Just(" And Friends"))
.map(v => v.toUpperCase())
.fold(Maybe.from)
.map(v => v + "!")
.fold(
    () => IO.of("--empty--"),
    greetings => IO(() => console.log(greetings))
)
.run();
// WELCOME, MONADS AND FRIENDS!

Wait, What's A "Monad"?

If you're already comfortable with Functional Programming (FP), and you're at least familiar with monads, and if the code snippet above doesn't scare you away, skip to "See Monio In Action". Or, if you're just looking for quick code examples of all the monads in Monio, check 'em out here!

But if terms like "higher-order function" or "monad" are confusing or intimidating to you, I encourage you to take some time first to build some comfort and familiarity; these are the foundations you need to get the most out of Monio.

I don't want you to feel intimidated. This isn't going to require you to speak in mathematical notation or re-learn everything you thought you knew about programming.

Well... to be clear, what I mean is, you don't have to do all that just to get started. There are small and comfortable baby steps you can begin taking to kick off the journey. The further you explore down the path, I think the more FP and monads will "hook" you, nudging and tugging you into different ways of thinking about and solving problems.



Now, it's time to dive into FP... and then Monads. But if you're already comfortable with FP, and ready to tackle learning monads specifically, you can jump directly to "Expansive Intro To Monads".

Make sure you take your time reading through that guide; it's pretty long and detailed, and there's a lot to digest.



See Monio In Action

To see how writing Monio-based code looks and feels, especially the use of IO/IOx monads (and all its variations), check out these demos. There's a variety of different approaches/styles demonstrated, which illustrate the flexibility Monio's monads offer.

Here's a full demo app (client and server) featuring Monio:

Monio Demo App

In addition, here's some live codepen demos:


Check out Monio's Monads for more example code snippets and detailed descriptions.

Overview

Monio balances the power of monads -- often dismissed by the non-FP programmer as academic and convoluted -- while pragmatically embracing the reality of the vast majority of JS programs: paradigm mixture (some OO, some FP, and probably a lot of imperative procedural code).

The driving inspiration behind Monio is the IO monad -- useful for managing side-effects -- that additionally supports "do-style" syntax with JS-ergonomic asynchrony (based on promises) in the style of familiar async..await code. IOs are lazy, so their operations are not triggered until the run(..) method is called.

Monio's IO is a transformer over promises, which means that when promises are produced in an IO, they are automatically unwrapped; of course, that means subsequent IO operations are deferred. If any IO in a chain produces a promise, run(..)'s result will be "lifted" to a promise that resolves when the entire IO chain is complete. Otherwise, the IO instance and its run(..) call will operate synchronously and immediately produce the result.

Monio intentionally chooses to model asynchrony over promises instead of Future monads, because of its goal of balancing FP with pragmatic and idomatic non-FP JS. However, there's nothing that should prevent you from using a Future monad with Monio if you prefer.

IO's "do-style" syntax is specified with the do(..) method (automatically lifts the IO to promise-producing asynchrony), which accepts JS generators (including "async generators": async function *whatever(){ .. }). yield is used for chaining IOs (which can produce promises to defer), whereas await is for explicitly deferring on a promise that's not already wrapped in an IO. The resulting style of code should be more broadly approachable for JS developers, while still benefitting from monads.

IO's do(..) is JS-ergonomic for exception handling: uncaught JS exceptions become promise rejections, and IO-produced promise rejections are try..catch'able. IO also supports modeling exception handling through Either monads: doEither(..) transforms uncaught exceptions into Either:Left values, and recognizes IO-produced Either:Left values as try..catch'able exceptions.

Monio's IO is also a Reader monad, which carries side-effect read environments alongside IO operations.

For the FP savvy

Monio's IO models a function e => IO a (Promise b c), which is strong enough to capture (optional) environment passing, side effects, async, and error handling without the pain of composing each type separately.

Typically IO does not take an argument, but given one, it acts like an effectful Reader. In addition, it can model sync or async functions so the inner Promise becomes optional.

In that way, you can think of it as ReaderT (IOT (Promise|Identity a b)) where Promise gets swapped for Identity if you're not doing async.

Monio's IO is like Scala's ZIO / RIO, where we have all the functionality we need wrapped up in a single monad kind.

Monio's Monads

Just("Are you ready for Monio?");

Check out Monio's Monads for a bunch of code snippets and detailed descriptions of all the monads (and helpers) provided in this library.

Using Monio

npm Module Module Format

To use monads/helpers from Monio, require(..) or import .. them by name:

Once Monio monads are imported into your module/program, instances are created from functions (no new constructors necessary):

var helloWorld = Just("Hello World");

helloWorld._inspect();
// Just("Hello World")

Just.is(helloWorld);
// true

Monio's monads can of course be used together in various expected ways:

var helloWorld = Just("Hello World");
var greeting = Maybe(helloWorld);
var log = str => IO(() => console.log(str));

var main = IO.do(function *main(){
    var msg = greeting.map(m => `${ m }!!`);

    // Uncomment this line to swap in an empty maybe
    // msg = Maybe.from(null);

    yield msg.fold(IO.of,log);
});

main.run();
// Hello World!!

Import/Require Paths For Monio Entities

Module Format

Note: For ESM-format usage in the browser, URL paths (with filename extensions!) or Import-Maps are required. To use the friendlier ESM-Node/CJS names while in the browser, an Import-Map is required. See above for explanation.

Here are the individual import / require named-entity paths:

Tests

A test suite is included in this repository, as well as the npm package distribution. The default test behavior runs the test suite using the files in src/.

  1. The tests are run with QUnit.

  2. To run the test utility with npm:

    npm test

Test Coverage

Coverage Status

If you have NYC (Istanbul) already installed on your system (requires v14.1+), you can use it to check the test coverage:

npm run coverage

Then open up coverage/lcov-report/index.html in a browser to view the report.

Note: The npm script coverage:report is only intended for use by project maintainers. It sends coverage reports to Coveralls.

License

License

All code and documentation are (c) 2024 Kyle Simpson and released under the MIT License. A copy of the MIT License is also included.