DEV Community

Discussion on: ✔||🤢 Commit or Vomit | checks.some()

Collapse
 
annervisser profile image
Anner Visser

I quite like the idea (and .some and .every are lovely), but this implementations is somewhat misleading to read:
All the checks are always performed at the time they're added, even though the power in some is that it break;s after the first hit.

I think this is a good opportunity for some higher level functions:

const checks = [
    (data) => data.age > 18,
    (data) => data.username.length > 6,
    (data) => {
        if (data.isNewUser) {
            return data.email !== undefined;
        } else {
            return  data.deleted === false;
        }
    }
];

const isInvalid = checks.some(check => !check(data));
Enter fullscreen mode Exit fullscreen mode

Overall I like the idea, but I think it will seldom be sufficient to deal with just a boolean as output. And if it is that simple, I'd prefer good ol' if/else.

So it's a 🤢 from me

Collapse
 
bugb profile image
bugb • Edited

The problem is how do you know what the piece of data that is invalid age or username or something (you need to have additional code). And what if you want to throw custom error message for each case?

Array in JS is also weird (if you dont know the spec of map or using Typescript)

a=[].map(v=>v.v.v.v.v.v) // it is valid
Enter fullscreen mode Exit fullscreen mode

It can cause debuging becomes nightmare!

So I prefer if-else.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited

Yea, this was my reaction as well; when a simple if isn't enough anymore, higher-order functions is the way to go.

However, I'd add the data as its own argument to make things more convenient:

const validate = validations => subject => validations.every(validation => validation(subject))

const confirmed = validate([ user => user.email_confirmed ])
const allowed = validate([ confirmed, user => user.age > 18  ])
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jmdejager profile image
🐤🥇 Jasper de Jager

good example! 😍

Collapse
 
jackmellis profile image
Jack

this 👍

Collapse
 
malikkillian profile image
MalikKillian

I'd prefer a ternary over the if-else, but changing the tests to a list of functions is excellent. Adding, updating, removing tests becomes dead simple at this point and it's easier to test.