cases-conds
v1.0.0
Published
Fluent interfaces to map cases to results, based on a test value
Downloads
8
Readme
Cases Conds
Use the conds expression to examine an object and return a corresponding result:
import { conds } from 'cases-conds';
const TEMPERATURE = 12;
const result = conds(TEMPERATURE)
.when(t => t < 0, 'Too low')
.when(t => t > 39, 'Too high')
.when(isNaN, 'Unknown temperature')
.otherwise('Alright');
// result => 'Alright'It also supports lazy results:
import { conds } from 'cases-conds';
const TEMPERATURE = 12;
const result = conds(TEMPERATURE)
.when(t => t < 0, () => 'Too low')
.when(t => t > 39, () => 'Too high')
.when(isNaN, () => 'Unknown temperature')
.otherwise(() => 'Alright');
// result => 'Alright'Lazy results are the way to throw errors:
import { conds } from 'cases-conds';
const TEMPERATURE = 12;
const result = conds(TEMPERATURE)
.when(t => t < 0, () => 'Too low')
.when(t => t > 39, () => 'Too high')
.when(isNaN, () => { throw new Error('Unknown temperature'); })
.otherwise(() => 'Alright');
// result => 'Alright'You can use the input object from the expression's head as part of the results:
import { conds } from 'cases-conds';
const TEMPERATURE = 12;
const result = conds(TEMPERATURE)
.when(t => t < 0, () => 'Too low')
.when(t => t > 39, () => 'Too high')
.when(isNaN, () => { throw new Error('Unknown temperature'); })
.otherwise(t => t + ' is alright');
// result => '12 is alright'There are situations in which using object literals to enable pattern matching has limitations:
const checkboxGroup = {
false: 'None selected',
undefined: 'Some selected',
true: 'All selected'
};
const result = checkboxGroup[undefined];
// Error: undefined cannot be used in indexerHowever, you can achieve the desired behavior with the cases expression:
import { cases } from 'cases-conds';
function getResult(checked?: boolean) {
return cases(checked)
.when(false, 'None selected')
.when(undefined, 'Some selected')
.otherwise('All selected');
}
const result = getResult(undefined);
// result => 'Some selected'The previous example wraps the cases expression into a function just to demonstrate the use of an union type. In real code, wrapping may be unnecessary.
