loading...

re: Nested Conditional Operators VIEW POST

FULL DISCUSSION
 

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()]
]);
 

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

code of conduct - report abuse