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

@theunderscorer/when

v1.0.1

Published

## What is "when" ?

Downloads

6

Readme

When ☝️

What is "when" ?

"when" is a simple utility function. Have you ever dealt with similar case?

const task = await getTask(taskId);

if (task.state === 'TODO') {
  handleTodo(task);
} else if (task.state === 'IN_PROGRESS') {
  handleInProgress(task);
} else if (task.state === 'DONE') {
  handleDone(task);
} else {
  throw new Error('Invalid task state.');
}

This could be improved by using switch or dictionary. Let's focus on second approach:

const stateHandlers = {
  TODO: () => handleTodo(task),
  IN_PROGRESS: () => handleInProgress(task),
  DONE: () => handleDone(task),
};

const task = await getTask(taskId);

if (stateHandlers[task.state]) {
  stateHandlers[task.state]();

  return;
}

throw new Error('Invalid task state.');

This requires additional boilerplate code however. Also, what if we would like to handle multiple task states with single function? That's where "when" comes to rescue! It gives you more flexible way of handling dictionaries. You can either use it to call function conditionaly:

import { when } from '@theunderscorer/when';

when(task.state, {
  'TODO, IN_PROGRESS': () => handleTodoOrInProgress(task),
  DONE: () => handleDone(task),
});

You can also use it to return value:

import { when } from '@theunderscorer/when';

const nextState = when(task.state, {
  TODO: 'IN_PROGRESS',
  IN_PROGRESS: 'DONE',
  DONE: () => {
    throw new Error('Invalid state provided.');
  },
});

"when" will find first key that matches given value.

You can also use else branch:

import { when, elseBranch } from '@theunderscorer/when';

const nextState = when(task.state, {
  TODO: 'IN_PROGRESS',
  IN_PROGRESS: 'DONE',
  DONE: () => {
    throw new Error('Invalid state provided.');
  },
  [elseBranch]: () => {
    // Handle every other task state
  },
});

Operators

In addition to handling simple dictionaries, "when" also lets you handle more complex cases.

Hint: Every operator is also provided as helper function.

In array

Matches if value can be found in array.

import { when } from '@theunderscorer/when';

when(task.state, {
  'TODO, IN_PROGRESS': () => handleTodoOrInProgress(task),
  DONE: () => handleDone(task),
});

Or as a helper function:

import { when, inArray } from '@theunderscorer/when';

when(task.state, {
  [inArray('TODO', 'IN_PROGRESS')]: () => handleTodoOrInProgress(task),
  DONE: () => handleDone(task),
});

Not in array

Matches if value cannot be found in array.

import { when } from '@theunderscorer/when';

when(task.state, {
  '! TODO, IN_PROGRESS': () => handleNotTodoAndNotInProgress(task),
  TODO: () => handleTodo(task),
});

Note: Mind space between "!" and values separated by a comma.

Or as a helper function:

import { when, notInArray } from '@theunderscorer/when';

when(task.state, {
  [notInArray('TODO', 'IN_PROGRESS')]: () =>
    handleNotTodoAndNotInProgress(task),
  TODO: () => handleTodo(task),
});

In range

Matches if value can be found between two numbers.

import { when, elseBranch } from '@theunderscorer/when';

when(payment.amount, {
  '0..1000': () => handleSmallPayment(),
  '1001..9000': () => handleBigPayment(),
  [elseBranch]: () => handleReallyBigPayment(),
});

Or as a helper function:

import { when, elseBranch, inRange } from '@theunderscorer/when';

when(payment.amount, {
  [inRange(0, 1000)]: () => handleSmallPayment(),
  [inRange(1001, 9000)]: () => handleBigPayment(),
  [elseBranch]: () => handleReallyBigPayment(),
});

Not in range

Matches if values cannot be found between two numbers.

import { when, elseBranch } from '@theunderscorer/when';

when(payment.amount, {
  '!0..1000': () => handleBigPayment(),
  '!1001..9000': () => handleSmallPayment(),
});

Or as a helper function:

import { when, notInRange } from '@theunderscorer/when';

when(payment.amount, {
  [notInRange(0, 1000)]: () => handleBigPayment(),
  [notInRange(1001, 9000)]: () => handleSmallPayment(),
});

Is

Matches if value "is" of a given type.

Hint: "is" accepts every type that is used in typeof

import { when, elseBranch } from '@theunderscorer/when';

when(unknownValue, {
  'is string': () => handleString(),
  'is number': () => handleNumber(),
  'is bigint': () => hangleBigInt(),
  'is symbol': () => handleSymbol(),
  'is boolean': () => handleBoolean(),
  'is undefined': () => handleUndefined(),
  'is object': () => handleObject(),
  'is function': () => handleFunction(),
  [elseBranch]: () => {
    throw new Error('Unknown type.');
  },
});

Or as a helper function:

import { when, is } from '@theunderscorer/when';

when(unknownValue, {
  [is('string')]: () => handleString(),
  [is('number')]: () => handleNumber(),
  // And so on...
});

Is not

Matches if value "is" not of a given type.

Hint: "is not" accepts every type that is used in typeof

import { when } from '@theunderscorer/when';

when(unknownValue, {
  '!is string': () => handleNotString(),
  '!is number': () => handleNotNumber(),
});

Or as a helper function:

import { when, isNot } from '@theunderscorer/when';

when(unknownValue, {
  [isNot('string')]: () => handleNotString(),
  [isNot('number')]: () => handleNotNumber(),
  // And so on...
});

License

This library is under MIT License.