Article 18QSX CodeSOD: Scrubbed Inputs

CodeSOD: Scrubbed Inputs

by
Remy Porter
from The Daily WTF on (#18QSX)

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 carevar 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.

proget-icon.png [Advertisement] High availability, Load-balanced or Basic - design your own Universal Package Manager, allow the enterprise to scale as you grow. Download and see for yourself! TheDailyWtf?d=yIl2AUoC8zAXZj4hNZnPgA
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments