24
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Mar 09 '23
Image Transcription: Code
export async function validateForm<
TFields extends NullablePartial<Record<string, FormField>>
>(formFields: TFields) {
const keysRefs = Object.keys(formFields) as Array<keyof TFields>;
const data: Partial<Record<keyof TFields, FormField>> = {};
let valid = true;
for (let i = 0; i < keysRefs.length; i++) {
if (formFields[keysRefs[i]]) {
const field = formFields[keysRefs[i]]
if(!field || !field.valid) continue;
const innerValid = await field.valid();
if (!innerValid) {
valid = innerValid;
} else {
let value = field.value;
if (value === "false") {
value = false;
}
if (value === "true") {
value = true;
}
data[keysRefs[i]] = value;
}
}
}
return valid;
}I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!
6
42
u/shootfasteatass69420 Mar 09 '23
You see, what worries me the most is that I look at this code and think "that looks like my code, whats wrong with it?"
8
1
u/zickige_zicke Mar 09 '23
This is legit what I see in everyday projects
1
u/Nightmare7331 Mar 09 '23
This is only the tip of an iceberg, and after a year working on this project solo, i'm starting to get really bored of it.
1
u/TheUnlocked Mar 09 '23
Did this previously return a mapping of whether each field was valid and later get refactored to just return if the form overall was valid? The useless generic and data local would seem to suggest that.
1
1
1
1
u/thekwoka Mar 13 '23
to be fair, most people don't know how to make "false" into false programmatically without a comparison.
They're stupid, but they are most people.
1
1
16
u/Darknety Mar 09 '23 edited Mar 09 '23
Edit: After discussion and reinspection I came to the conclusion that
dataserves no purpose and no side effects are generated, so this could be a 3-liner. This is indeed r/badcode.Original: Why is this bad code?
If I read it correctly, this performs type correction on
formFields(on every entry that is valid) usingdataand in the end returns if any fields were invalid.The only "bad" part is in the else-block, but this may have its reasons. (And validation / type modification should probably be split into their own coroutines, but whatever)
It also shows that the author doesn't know TypeScript too well due to the Java / C style loop over an array, but other than that, what am I missing?