DEV Community

loading...

Discussion on: Nested Conditional Operators

Collapse
ramblingenzyme profile image
Satvik Sharma

If you want to write this style of code, I'd prefer using cond from lodash which reimplements cond from Lisp.

const validateInput = _.cond([
    [({ field1 }) => !field1, Promise.reject('Missing field 1')],
    [({ field2 }) => !Array.isArray(field2), Promise.reject('field2 is not an array')],
    [({ field3 }) => !isValidType(field3), Promise.reject('field3 is invalid')],
    [_.stubTrue, Promise.resolve()]
]);

Edit: didn't realise it was an object, not an array.

Could even do something like this:

const isMissing = key => obj => !obj[key];
const notArray = key => obj => !Array.isArray(obj[key]);
const notType = (type, key) => obj => typeof obj[key] !== type;

const validateInput = _.cond([
    [isMissing('field1'), Promise.reject('Missing field 1')],
    [notArray('field2'), Promise.reject('field2 is not an array')],
    [notType('string', 'field3'), Promise.reject('field3 is invalid')],
    [_.stubTrue, Promise.resolve()]
]);
Collapse
avalander profile image
Avalander Author

This is a great suggestion, I actually ended up doing something similar with Ramda's cond