|
|
|
|
|
by _davidchambers
3989 days ago
|
|
These two functions are equivalent: const f1 = function(s) {
let data;
try {
data = JSON.parse(s);
} catch (err) {}
if (data != null &&
data.a != null &&
data.a.b != null &&
typeof data.a.b.c === 'string') {
let x = parseFloat(data.a.b.c);
if (x === x) {
return x;
}
}
return null;
};
const f2 =
R.pipe(S.parseJson,
R.chain(S.gets(['a', 'b', 'c'])),
R.filter(R.is(String)),
R.chain(S.parseFloat),
S.fromMaybe(null));
Note that in the first function we have an unsafe expression, data.a.b.c
which we must guard with null/undefined checks. Unsafe expressions can easily get out of sync with their corresponding guards.We can apply functional programming concepts to JavaScript code to obviate the need for null/undefined checks. The fact that we can't have all the benefits of FP in JS shouldn't dissuade us from taking advantage of the ideas which are applicable. |
|
(Also, you picked an odd task - it's unusual to expect a float to be represented as a string in a JSON object, and a check that rejects NaN but accepts weird floats like Infinity is not terribly useful.)