For me it was the second. Am I the only one ?
For me it was the second. Am I the only one ?
The whole thing about the way it's written with throwing/catching is a red herring anyway, you should just replace those with a different choice of if's. If you're feeling super adventurous, you can instead replace them with goto's, which is kinda funny; it would actually simplify the code, how often do you see that?
There are very good reasons to prefer Result over exceptions, but this example is not one.
let v = Number.parseInt("a3", 10);
try {
if (Number.isNaN(v)) {
throw new Error("NaN");
} else if (v > 3) {
throw new Error("gt 3");
}
v += 1;
} catch (error) {
v = 3;
}
v += 1;
Or writing a "guard function" that throws ... function throwIfNaNorGt3(v) {
if (Number.isNaN(v)) {
throw new Error("NaN");
} else if (v > 3) {
throw new Error("gt 3");
}
}
let v = Number.parseInt("a3", 10);
try {
throwIfNaNorGt3(v);
v += 1;
} catch (error) {
v = 3;
}
v += 1;But both are terrible. It should just be a bunch of if (...) { ... } else if (...) { ... } else { ...} etc. with no mutation of variables (what are all those v += 1 for?).
1. Parse an integer N from a string.
2. If N is NaN, fail with an error. Otherwise, increment N by 1.
3. If N is > 3, fail with an error. Otherwise, increment N by 1.
4. If steps 1-3 failed, set N to 3.
5. Increment N by 1.
Those are quite strange requirements, and the resulting second code looks strange too, but... it faithfully and obviously correctly represents the given specification.Thank you for the comments. I've learned more from reading the comments.
I mean if you start with a set of tests instead of pseudocode written down in text you could probably write something smarter.