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

conditional-reduce

v1.2.0

Published

Construct a JavaScript expression that returns a value based on an enumerated list of possible values

Downloads

384

Readme

Conditional Reduce

Like map-reduce, but for branching logic. Like a switch statement, except it's an expression that returns a value. This little helper module allows you to construct a JavaScript expression that returns a value based on an enumerated list of possible values.

This module was inspired by a conversation on dev.to with Avalander and John Papa. Thanks you two!

Installation

Install with npm:

npm install conditional-reduce

Usage

Direct usage

In JavaScript:

const { reduce } = require('conditional-reduce');

console.log(reduce('dog', {
  dog: () => 'Dogs are great pets',
  cat: () => 'Cat\'s are also great'
})); // Prints "Dogs are great pets"

console.log(reduce('bird', {
  dog: () => 'Dogs are great pets',
  cat: () => 'Cat\'s are also great'
})); // Throws 'Invalid conditional value "bird"' exception

In TypeScript:

import { reduce } from 'conditional-reduce';

console.log(reduce<string>('dog', { // generic enforces string return type on all branches
  dog: () => 'Dogs are great pets',
  cat: () => 'Cat\'s are also great'
})); // Prints "Dogs are great pets"

console.log(reduce<string>('bird', {
  dog: () => 'Dogs are great pets',
  cat: () => 'Cat\'s are also great'
})); // Throws 'Invalid conditional value "bird"' exception

Curry'd usage

If you want to reuse your conditional, you can curry them with the curry function.

In JavaScript:

const { curry } = require('conditional-reduce');

const dogReducer = curry({
  dog: () => 'Dogs are great pets',
  cat: () => 'Cat\'s are also great'
});

console.log(dogReducer('dog')); // Prints "Dogs are great pets"
console.log(dogReducer('bird')); // Throws 'Invalid conditional value "bird"' exception

In TypeScript:

import { curry } from 'conditional-reduce';

const dogReducer = curry<string>({
  dog: () => 'Dogs are great pets',
  cat: () => 'Cat\'s are also great'
});

console.log(dogReducer('dog')); // Prints "Dogs are great pets"
console.log(dogReducer('bird')); // Throws 'Invalid conditional value "bird"' exception

Default Values

You can specify a default value, like a switch statement's default case, by adding an extra case function at the end.

In JavaScript:

const { reduce } = require('conditional-reduce');

console.log(reduce('bird', {
  dog: () => 'Dogs are great pets',
  cat: () => 'Cat\'s are also great'
}, (value) => `Your pet ${value} is probably cool too`));

In TypeScript:

import { reduce } from 'conditional-reduce';

console.log(reduce<string>('bird', { // generic enforces string return type on all branches
  dog: () => 'Dogs are great pets',
  cat: () => 'Cat\'s are also great'
}, (value: string) => `Your pet ${value} is probably cool too`)); // Prints "Your pet bird is probably cool too"

API

Note: the signatures below use the TypeScript definitions for clarity. The types are not enforced in pure JavaScript, so in theory you can mix and match, but honestly I never tested that scenario and have no idea what will happen.

If you're not familiar with TypeScript syntax, there are basically three things you need to know:

  1. A variables type is specified after the variable name, and separated by a :. For example, x: number means we have a variable named x, and it's a number.
  2. A ? after the variable name and before the : means that the variable is optional
  3. A variable name or type followed by <T> means that it takes in a generic type called T, i.e. a placeholder type that the caller fills in. T can be any type, but all references to T are of the same type, whatever it may be. This type is supplied by the user when calling the function (see TypeScript examples above).

IConditionalDictionary

Signature:

interface IConditionalDictionary<T> {
  [ key: string ]: () => T;
}

Description:

Conditional dictionaries are at the core Conditional Reduce. These are analogous to the case statements in a switch statement.

Each key in the dictionary is one of the possible values to be matched against in reduce(). The value is a function that takes no parameters, and returns a value. This returned value is then returned by reduce() to the calling code.

reduce(value, conditionals, defaultCase)

Signature:

function reduce<T>(
  value: string,
  conditionals: IConditionalDictionary<T>,
  defaultCase?: (value: string) => T
): T

Description:

This function immediately reduces the conditionals dictionary to a single return value. If value is not present in the dictionary, one of two things can happen:

  1. If defaultCase is specified, then that function is invoked. The value parameter passed to reduce() is passed along to the defaultCase function for your use, if desired. The value returned from defaultCase is then returned from reduce
  2. If defaultCase is not specified, then an exception is thrown

curry(conditionals, defaultCase)

Signature:

function curry<T>(
  conditionals: IConditionalDictionary<T>,
  defaultCase?: (value: string) => T
): (value: string) => T

Description:

This function splits the reduce() call into two steps. The first creates the conditional case, with an optional default case. The parameters supplied here behave identically to their counterparts in reduce. A function is returned that you can then pass a value to, which then behaves like reduce().

This function is implemented under the hood as a pass through to reduce:

function curry(conditionals, defaultCase) {
  return (value) => reduce(value, conditionals, defaultCase);
}

License

MIT License

Copyright (c) Bryan Hughes <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.