In this age of JavaScript everywhere, developers have to come up with all sorts of ways to work around the uglier segments of JavaScript. For example, Aaron found this block, which promises to scrub “false-y” fields.
require _ = require("underscore");
// recurses, use with care
var scrubFalseyFields = function (obj) {
return _.chain(obj)
.pairs()
.filter(function (pair) {
var val = pair[1];
if (_.isObject(pair[1])) {
// recurse!
pair[1] = scrubFalseyFields(val);
}
return val;
})
.object()
.value();
};
Now, for those of you that don’t know your way around Underscore, a functional utility-belt for JavaScript list manipulation, the first call, chain
, just enables chained calls to the library by wrapping obj
.
pairs
takes an object, in the form {foo: 5, bar: 6}
and converts it into an array in the form [["foo", 5], ["bar", 6]]
. object
is its inverse, and value
ends the chain. filter
, obviously is for filtering, but what happens here is a little… odd.
filter
will get an input like ["foo", 5]
, and then grab the value segment- 5
in this case. We’ll use that value to decide whether or not to include this pair in the output object- so at its simplest level, this function just takes an object and removes any fields from it that are false-y, and it does that recursively.
There was only one real problem with this code: it was being used to sanitize input data that might contain false values. Downstream from this, there were huge piles of code to handle all the inevitable undefined
issues that this created.