Issue
Can the following code be simplified for readability, simplicity, or any other way? Specifically, can this be written without checking for undefined on every line?
These ok statements are only some of the many filters that are checked, so this list is large and unruly.
const aOk = data?.a ? data.a.includes(a) : true
const bOk = data?.b ? data.b <= b : true
const cOk = data?.c ? data.c >= c : true
const dOk = data?.d ? data.d === d : true
const eOk = data?.e ? data.e === e.toString() : true
if (
aOk &&
bOk &&
cOk &&
dOk &&
eOk
) {
return true
}
return false
Solution
If the shape of validation doesn't change often, I don't see a problem with your function. As another poster mentioned you can instead create a list of functions. Something like this:
type TData = {
a: number[];
b: number;
c: number;
d: number;
e: string;
};
const data = {
a: [3],
b: 4,
c: 4,
d: 1,
e: "9",
};
const validators: (data:TData, v: { [k in keyof TData]: number }) => {
[k in keyof TData]: () => boolean;
} = (v) => ({
a: () => data.a.includes(v.a),
b: () => data.b <= v.b,
c: () => data.c >= v.c,
d: () => data.d === v.d,
e: () => data.e === v.e.toString(),
});
const all = () => {
for (const k of Object.values(validators(data, otherData))) {
if (!k()) return false;
}
return true;
};
Answered By - windowsill
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.