npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

funpro

v1.0.1

Published

Be functional by using union types, pattern matching, and pure side-effects

Downloads

21

Readme

FunPro

A fun, light-weight and zero-dependency lib for functional programming in JS.

FunPro weighs about 1KB and integrates with Ramda and partly the Fantasyland Spec. Inspired by Elm, Haskell, Folktale and the legendary Prof. Frisby.

npm i -S funpro

pick your style of importing in your JS code:

// commonJS
const { union, matchWith, Maybe, Result, Task } = require('funpro');

// ES6
import { union, matchWith, Maybe, Result, Task } from 'funpro';

// browser
<script src="/dist/main.umd.js"></script>
<script>const { Maybe } = window.FunPro;</script>

Also check out:

  • the guide, with JS FP background, tips and usage examples
  • the official API docs

Union types (Algebraic data types)

Union types or ADTs let you model your domain more precisely than with other data type primitives like boolean, strings or integers.

An optional value can use the Maybe type.

const listHead = list =>
  list.length === 0 ? Maybe.Nothing() : Maybe.Just(list[0]);

An operation that may fail can be represented with a Result. Maybe, Result

This let's you write super safe functions like this:

const safeJsonParse = val => {
  try {
    return Result.Ok(JSON.parse(val));
  } catch (e) {
    return Result.Err(e);
  }
};

You don't have to worry about the error and map away. At some point you pattern match to handle the different cases.

This could also be thinkable:

const safeDate = val => {
  try {
    return Result.Ok(new Date(val));
  } catch (e) {
    return Result.Err(e);
  }
};

No more weird try catch blocks. Yay! :-)

No how do I use the values when they are wrapped into a context like that?

The answer is pattern matching:

const maybePrice = getItemPrice(item); // returns a Maybe with the price or Nothing

const displayPrice = matchWith(maybePrice, {
  Just: val => `${val.toFixed(2)} $`,
  Nothing: () => 'not for sale',
})

There are also functions to map, chain, etc with these types.

Custom union types

It's also possible to create your own union types. Using boolean to model things is very limited, especially if you need more than two states. So for a page you could use something like this.

// for each value specify the number of arguments it can carry.
const PageState = union({
  Loading: 0,
  Loaded: 1,
  Errored: 1,
})

Loading doesn't need any arguments. Loaded will need some sort of content. Errored should contain some kind of error message or reason why it failed.

With pattern matching all the cases can be handled it one place.

// create a pageState
// this could also be Page.Loading() or Page.Errored('Oh no!')
const pageState = PageState.Loaded({ user: {name: 'Peter', age: 42} });

const pageContent = matchWith(pageState, {
  Loading: () => 'Loading...',
  Loaded: ({ user: { name, age } }) => `${name} is ${age} old`,
  Errored: msg => `Something went wrong: ${msg}`,
})

This is much more powerful than the dull ON/OFF logic that booleans provide.

Give booleans the finger and make impossible states impossible.

IO and Async management

To keep your code free of side-effects this lib gives you s Task for asynchronous things and basically anything that would be considered a side-effect.

Why not a Promise?

Promises always execute their action upon creation. There is no real way for operating on a promise without already kicking of the first task.

Tasks won't to anything until you pull the trigger and call .run(). This allows you to map or chain or pass around your task while knowing it will only be execute when run is called.

Ideally you only call run once in your entire program and chain or map other tasks onto the initial one. That way you can make sure that you're entire code does not have side-effects except for that isolated place where you call .run().

// function that kicks of your app
const startApp = () => loadAssets();
main = Task.of(startApp)
  .chain(() => fetchDataTask)
  .onError(err => {
    // catch or log the error
  })

// then run it somewhere
main.run()

Random

The mission

I think FP is awesome, this is my attempt to sneak more FP code into the JS world. If I could choose I, would prefer a true function language like Elm or Haskell, but sometimes there is no way around JS and luckily, it is also very capable of writing some FP code.

What's up with the name?

Apparently there are no cool names availbale on npm anymore. Then all of a sudden I realized, that when taking the first 3 letters from functional and programming, you get the words fun and pro. Tah-Dah.