3 ms·
Technically you could just use an assignment ternary expression for this: const y = (x === true) ? true : false; I used this kind of style for argument in
by cookiengineer 1y ago
Technically you could just use an assignment ternary expression for this:
const y = (x === true) ? true : false;
I used this kind of style for argument initialization when I was writing JS code, right at the top of my function bodies, due to ES not being able to specify real nullable default values. (and I'm setting apart why I think undefined as a value is pointless legacy).
Composite.prototype.SetPosition(x, y, z) {
x = (isNumber(x) && x >= 0 && x <= 1337) ? x : null;
y = (isNumber(y) && y >= 0 && y <= 1337) ? y : null;
z = isNumber(z) ? z : null;
if x !== null && y !== null && z !== null {
// use clamped values
}
}
- NathanaelRea 1y agoI typically only use ternaries for single operations and extract to a function if it's too big. Although they are quite fun in JSX. For your code i'd probably do: function SetPosition(x, y, z) { if (!(isNumber(x) && isNumber(y) && isNumber(z))) { // Default vals return; } x = clamp(x, 0, 1337); y = clamp(y, 0, 1337); z = z; }
- cookiengineer 1y agoI always call this the difference of return branch styles. Yours I'd describe as "fast fail" aka return false as quickly as possible (for lack of a better terminology) whereas I personally prefer to have a single return false case at the bottom of my function body, and the other validation errors (e.g. in Go) are usually in the else blocks. In JS, errors are pretty painful due to try/catch, that's why I would probably these days recommend to use Effect [1] or similar libraries to have a failsafe workflow with error cases. Errors in general are pretty painful in all languages in my opinion. The only language where I thought "oh this might be nice" was Koka, where it's designed around Effect Types and Handlers [2] [1] https://effect.website/ https://effect.website/ [2] https://koka-lang.github.io/koka/doc/index.html https://koka-lang.github.io/koka/doc/index.html
- fuzzythinker 1y agonitpick: cleaner w/o ()'s, as '=' is the 2nd lowest operator, after the comma separation operator.
- cookiengineer 1y agoI guess I'm that one guy that likes expression brackets and statement ending symbols.