Need private packages and team management tools?Check out npm Teams »

cond-xtra

1.0.0 • Public • Published

cond-xtra

Cond construct with some minor conveniences added.

API

cond(...clauseList, default)

Iterate through a series of clauses until one of them has a true predicate. Predicates and return values can both be closures in order to evaluate them lazily. If it's necessary to return a function as a value, cond.value can be used to wrap it, or it can be returned from another anonymous function. If none of the clauses has a true predicate, returns the last clause as the default.

Example

const resType = 'application/json;charset=utf-8';
const message = cond(
    // clauses can have pre-evaluated predicates and values
    [resType.includes('json'), 'it\'s json'],
    // one or both may be closures for lazy evaluation; especially helpful for
    // error checking
    [() => resType.includes('text'), () => 'it\'s text'],
    // Entire clause may be in a closure; both parts will be evaluated at the
    // same time, but only when this clause is reached
    () => [resType.includes('xml'), 'it\'s xml'],
    // Default may be a literal or a closure
    `I dunno what it is, but the header says ${resType}`
); // -> 'it\'s json'

cond.value(any)

Wraps a return value so it isn't accidentally evaluated when its predicate is true. This should be used for any x for which x instanceof Function is true. This can wrap any value, but is only useful for callable return values.

Example

const order = 'asc'
const sortingFunc = cond(
    [order === 'desc', cond.value((a, b) => a - b)],
    [order === 'asc', cond.value((a, b) => b - a)],
    cond.value((a, b) => 0)
); // -> [Function]

cond.nd(...clauseList)

Same as cond.multi, but automatically provides null as the default value.

Example

const message = cond(
    [false, 'this will never be seen'],
    ['', 'not this one, either'],
    [0, 'nope']
    // No default clause needed
); // -> null

cond.multi(...clauseList, default)

Returns an Array containing the return values for all clauses with true predicates. Same lazy evaluation rule holds from regular cond. If no clauses have a true predicate, returns the last clause with no array.

Example

const bestVegetables = cond.multi(
    [false, 'green beans'],
    [true, 'broccoli'],
    [false, 'cauliflower'],
    [true, 'snow peas'],
    ['carrots']
); // -> ['broccoli', 'snow peas']

cond.multind(...clauseList)

Same as cond.multi, but automatically provides null as the default value.

Example

const bestVegetables = cond.multi(
    [false, 'green beans'],
    [false, 'broccoli'],
    [false, 'cauliflower'],
    [false, 'snow peas'],
    // no default needed
); // -> null

Keywords

Install

npm i cond-xtra

DownloadsWeekly Downloads

1

Version

1.0.0

License

ISC

Unpacked Size

19.5 kB

Total Files

8

Last publish

Collaborators

  • avatar