
Security News
Crates.io Implements Trusted Publishing Support
Crates.io adds Trusted Publishing support, enabling secure GitHub Actions-based crate releases without long-lived API tokens.
conditional-reduce
Advanced tools
Construct a JavaScript expression that returns a value based on an enumerated list of possible values
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!
Install with npm:
npm install conditional-reduce
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
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
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"
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:
:
. For example, x: number
means we have a variable named x
, and it's a number.?
after the variable name and before the :
means that the variable is optional<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).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.
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:
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
defaultCase
is not specified, then an exception is thrownSignature:
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);
}
MIT License
Copyright (c) Bryan Hughes <bryan@nebri.us>
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.
1.2.0 (2019-5-20)
curry
and reduce
.FAQs
Construct a JavaScript expression that returns a value based on an enumerated list of possible values
The npm package conditional-reduce receives a total of 142 weekly downloads. As such, conditional-reduce popularity was classified as not popular.
We found that conditional-reduce demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Crates.io adds Trusted Publishing support, enabling secure GitHub Actions-based crate releases without long-lived API tokens.
Research
/Security News
Undocumented protestware found in 28 npm packages disrupts UI for Russian-language users visiting Russian and Belarusian domains.
Research
/Security News
North Korean threat actors deploy 67 malicious npm packages using the newly discovered XORIndex malware loader.