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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@idiosync/fswitch

v1.0.25

Published

A functional switch statement with familiar syntax

Downloads

42

Readme

NPM Version

fSwitch

Initially created for handling server statuses in a nice readable way, it generalises as a system for implementing complex conditional code in a easy-to-read and self-documenting manner.

// use with redux-saga
yield fSwitch(res.status,
  [SUCCESS, () => put(successAction)],
  [FAIL, () => put(failAction)],
  () => put({ type: 'error', error: new Error('summin went wrong') })
)

Installation

yarn:

$ yarn add @idiosync/fswitch

npm:

$ npm i @idiosync/fswitch

Basic use

The fSwich function accepts an input followed by a series of conditional functions and callbacks. Like a switch statement the first passing case terminates the process. Finally, a default callback can be passed.

import { fSwitch, fCase, fDefault } from "@idiosync/fswitch"

const person = { age: 45, name: James };

const NAME_IS_RICHARD = person => person.name === 'rechard'
const IS_YOUNGER_THAN_18 = person => person.age < 18

fSwitch(person,
  fCase(NAME_IS_RICHARD, person => saveToRichardPool(person)),
  fCase(IS_YOUNGER_THAN_18, person => tooYoung(person),
  fDefault(person => person.isHappy = true)
)

The above statement can also be written in a short from

fSwitch(
  person,
  [NAME_IS_RICHARD, (person) => saveToRichardPool(person)],
  [IS_YOUNGER_THAN_18, (person) => tooYoung(person)],
  (person) => (person.isHappy = true)
);

The fSwitch function returns whatever is returned by the successful callback. Amongst other things this can useful for asynchronous effects.

// await promise returned by successful callback
await fSwitch(
  input,
  fCase(SOME_STATE, async (input) => fetch(input)),
  fDefault(async (input) => fetch(input))
);

Server status codes

fSwitch was initially created for dealing with server status codes in redux-saga, so I will use that as an example.

All common server codes are supported and listed here: responses.

// import some error cases
import { SUCCESS, FAIL } from "@idiosync/fswitch";

// create our own conditional if we needed
// (although 404 and all other common codes are actually in above file too)
const IS_404 = (status) => status === 404;

function* fetchUserInfoSaga() {
  const res = yield fetch(url);

  yield fSwitch(
    res.status,
    [SUCCESS, () => put(successAction)],
    [IS_404, () => put(server404Action)],
    [FAIL, () => put(failAction)],
    () => put({ type: "error", error: new Error("summin went wrong") })
  );
}

If you need a more complex callback you can return a generator or another saga. This allows you to effectively yield from the callback

import { fSwitch, SUCCESS } from "fswitch";
import { put, call } from "redux-saga/effects";

function* fetchUserInfoSaga() {
  const res = yield fetch(url);

  yield fSwitch(
    res.status,
    [
      SUCCESS,
      // callback returns a generator wrapped with saga's "call" function
      (status) =>
        call(function* () {
          if (status === 202) {
            yield put(someAction);
          } else {
            yield put(someOtherAction);
          }
        }),
    ],
    () => put(failAction)
  );
}

Remember that once a case passes the later ones are not called, so if you want to use SUCCESS or FAIL conditions then you will have to handle individaul calls first.

fSwitch(
  res.status,
  [SUCCESS, handleSuccess],
  [s200, handle200] // <--- this line will never be reached
);

Combiners

These are functions that combine multiple conditions with and / or logic.

fSwitch(
  status,
  [or(s200, s202), handleSuccess],
  [and(isMoreThan202, isLessThan300), handleSuccessDifferently],
  [FAIL, handleFail]
);

Try/Catch

For the sake of pretty syntax I have added an optional try/catch wrapper. If you use this you MUST use the catch function returned by try or fSwitch will never be called

  yield fSwitch.try(res.status,
    [ SUCCESS, () => throw new Error("error")],
    () => defaultAction()
  ).catch(
    error => handleError(error)   // <-- error is caught here
  )