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

condition-switch

v0.1.2

Published

A powerful and flexible TypeScript utility for writing clean, declarative, and expressive conditional logic. It's a great replacement for if/else and switch statements in functional components, arrow functions, and other expression-based scenarios.

Readme

Conditional Switch 🚦

npm version

A flexible and powerful TypeScript utility for conditional rendering and logic, inspired by functional programming patterns. condSwitch allows you to write clean, declarative, and expressive conditional logic, especially in scenarios where traditional if/else or switch statements can be verbose or cumbersome.

Table of Contents

🚀 Features

  • Declarative Style: Write more readable and maintainable code.
  • Lazy Evaluation: Conditions and values can be functions, delaying their execution until needed, which can be a performance boost.
  • Type-Safe: Written in TypeScript to ensure type safety.
  • Flexible: Supports both object and array-based condition-value pairs.
  • Default Value: Provides a fallback default value.

📦 Installation

npm install condition-switch
# or
yarn add condition-switch
# or
pnpm add condition-switch

💡 Usage

Basic Usage

condSwitch takes an array of condition-value pairs and a default value. It returns the value of the first condition that evaluates to true.

1. Array of Objects ({ condition, value })

import condSwitch from 'condition-switch'

const result = condSwitch(
  [
    { condition: false, value: 'Not this one' },
    { condition: true, value: 'This is it!' }
  ],
  'Default value'
)

console.log(result) // "This is it!"

2. Array of Tuples ([condition, value])

import condSwitch from 'condition-switch'

const result = condSwitch(
  [
    [false, 'Not this one'],
    [true, 'This is it!']
  ],
  'Default value'
)

console.log(result) // "This is it!"

⚡️ Lazy Evaluation with Functions

For performance-critical sections, you can use functions for conditions and values. This ensures that they are only executed when necessary.

import condSwitch from 'condition-switch'

const expensiveCalculation = () => {
  console.log('Performing expensive calculation...')
  return 42
}

const result = condSwitch(
  [
    [() => false, 'Not this one'],
    [() => true, expensiveCalculation]
  ],
  'Default value'
)

console.log(result)
// "Performing expensive calculation..."
// 42

🤖 API

condSwitch<T, DefaultT>(conditionWithValues, defaultValue)

  • conditionWithValues (ConditionWithValue<T>[]): An array of condition-value pairs.
    • ConditionWithValue<T> can be:
      • { condition: unknown, value: T | (() => T) }
      • [unknown, T | (() => T)]
  • defaultValue (DefaultT | (() => DefaultT)): The value to return if no conditions are met. Can also be a function for lazy evaluation.

Type Aliases

  • Condition (unknown): Any value that can be evaluated for truthiness.
  • Value<T> (T | (() => T)): A value or a function that returns a value.

✨ Use Cases

React

import condSwitch from 'condition-switch'

const MyComponent = ({ isLoading, isError, data }) => {
  return (
    <div>
      {condSwitch(
        [
          { condition: isLoading, value: () => <LoadingSpinner /> },
          { condition: isError, value: () => <ErrorMessage /> },
          { condition: data, value: () => <Content data={data} /> }
        ],
        () => (
          <NoDataMessage />
        )
      )}
    </div>
  )
}

Vanilla JavaScript

import condSwitch from 'condition-switch'

const getGreeting = (hour) => {
  return condSwitch(
    [
      [hour < 12, 'Good morning'],
      [hour < 18, 'Good afternoon']
    ],
    'Good evening'
  )
}

console.log(getGreeting(10)) // "Good morning"

🏆 Best Practices

  • Use functions for expensive operations: For values that are computationally expensive to generate, use a function to delay the execution until the condition is met.
  • Keep conditions simple: For readability, it's best to keep the conditions as simple as possible. If you have complex logic, consider extracting it into a separate function.
  • Use the object format for clarity: When you have many conditions, using the { condition, value } format can make your code more self-documenting.

🗺️ Roadmap

  • [ ] Add support for more complex conditions (e.g., pattern matching).
  • [ ] Explore optimizations for performance.
  • [ ] Add more examples and use cases to the documentation.

🤝 Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.

📜 License

This project is MIT licensed.