April 28, 2011

jQuery.trim

Do you want to know how the trim method works in jQuery? Today is lucky day.

Here's the code from the jQuery 1.5.2 source, I separated distant lines of code with three dots:
...
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,

// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
...
// Save a reference to some core methods
...
trim = String.prototype.trim,
...
// Use native String.trim function wherever possible
trim: trim ?
    function( text ) {
        return text == null ?
            "" :
            trim.call( text );
    } :

    // Otherwise use our own trimming functionality
    function( text ) {
        return text == null ?
            "" :
            text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
    },
...
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
    trimLeft = /^[\s\xA0]+/;
    trimRight = /[\s\xA0]+$/;
}
...

Line 14 is where the ternary action to determine how $.trim will behave begins, all the way through line 26. Another way to look at it is this:
trim: trim ?
    function( text ) {
        // native trimming
    } :
    function( text ) {
        // jQuery trimming
    },

You might find trim: trim hard to understand, but not when you look at the trim variable in line 11. Notice how jQuery stores an internal reference to the native trim method of strings. So, if we have native support for trimming, i.e. checking for truthy value in the trim variable, we go ahead and do it that way but not before checking for null or undefined.

If the browser doesn't have support, we'll check if the passed string is not null or undefined, if it is, we'll return a blank string (just like in the first case), otherwise we'll trim it. Let's see how.

We're calling the toString method on the passed string to, and this is a total guess, make sure we have a string to work with before attempting any operation.

Then we'll trim the left side of the string and after that the right side. The regular expressions for those (in lines 6 & 7) match, pretty much, every type of space you wouldn't want in your string. So, we make sure that the passed string doesn't have those, and if it does, we get rid of them by replacing them with a blank string.

We're just missing lines 2-3 and 28-32. rnotwhite matches a single character other than white space and lines 28-32 check if we should be checking for non-breaking spaces (A0 in hexadecimal) in our trimming, mostly because of IE like the comment says. If so, we need to redefine our trimLeft and trimRight to include matching the non-breaking space character.

Hopefully I'm right about some of this but if not, let me know in the comments.

Thanks for reading.

Sources:
jQuery 1.5.2 source code
jQuery API - jQuery.trim()

April 21, 2011

jQuery.parseJSON

The other day I was re-watching (haha, learning through repetition) "11 More Things I Learned from the jQuery Source" and this time I was quite amazed when Paul Irish talked about parseJSON. And the reason was the way jQuery makes the JSON object, it's clever, it's very clever.

Let me show you. Here's jQuery's 1.5.2 parseJSON method:
parseJSON: function( data ) {
    if ( typeof data !== "string" || !data ) {
        return null;
    }

    // Make sure leading/trailing whitespace is removed (IE can't handle it)
    data = jQuery.trim( data );

    // Make sure the incoming data is actual JSON
    // Logic borrowed from http://json.org/json2.js
    if ( rvalidchars.test(data.replace(rvalidescape, "@")
        .replace(rvalidtokens, "]")
        .replace(rvalidbraces, "")) ) {

        // Try to use the native JSON parser first
        return window.JSON && window.JSON.parse ?
            window.JSON.parse( data ) :
            (new Function("return " + data))();

    } else {
        jQuery.error( "Invalid JSON: " + data );
    }
},

Let's dissect that:
  • Lines 2-4 are just checking you pass a string and its not empty.
  • Line 7 explains itself.
  • Lines 11-13 is a regular expression evaluation to make sure we have valid JSON.

The interesting part, in this case, is the return statement:
return window.JSON && window.JSON.parse ?
    window.JSON.parse( data ) :
    (new Function("return " + data))();

If the browser has native JSON support, use that. If not, and this is the interesting part, we'll do (new Function("return " + data))()

But what does that mean? I'm glad you asked.
  • We're calling the Function constructor, which will return a Function object (function reference) and immediately invoke it.
  • The Function constructor takes an "n" number of arguments that will become the function's parameters, being the last one the body of the function. We're passing only one parameter, meaning "return " + data will become the function's body.
  • What does the constructed function do then? Considering data is a JSON string it becomes rather obvious now. It returns a JavaScript object.
See? I told you it was clever, no need for eval() this way.

Thanks for reading and let me know your comments.

Source:
11 More Things I Learned From The jQuery Source by Paul Irish
Function - MDN

April 19, 2011

Beware of Assholes

What is an asshole?
  • Someone who either intentionally or unintentionally infuriates/demeans/damages their peers/superiors/underlings.
  • There are two flavors: Temporary and Certified assholes. A temporary asshole is someone who is probably having a bad day or a bad moment. Certified assholes are persistently nasty and destructive jerks.

Why are they dangerous?
  • Remember how they can damage people? well, at times that includes clients and customers.
  • They undermine organizational performance.
  • Asshole poisoning is a contagious disease that anyone can catch. Once you unleash disdain, anger and contempt or someone else unleashes it on you, it spreads like wildfire.

What should you care?
  • The total costs of assholes are HIGH. From loss of motivation, higher stress and turnover to legal and HR management costs like inside and outside counsel.
  • If you sap the energy out of people, you may be sucking the life out of your career.
  • When people feel mistreated and dissatisfied with their jobs, they are unwilling to do extra work to help their organization.
  • Writing, displaying and repeating words about treating people with respect, but allowing or encouraging the opposite behavior, is worse than useless. The organization and its leaders are seen as hypocrites, which fuels cynicism and scorn.
  • Organizations that drive in compassion and drive out fear attract superior talent, share ideas more freely, have less dysfunctional internal competition, and trump the external competition.

What should you do?
  • Adopt The No Asshole Rule.
  • Have yourself tested.
  • Get rid of assholes fast.
  • Treat certified assholes as incompetent employees.
  • Model and teach constructive confrontation.
  • Improve your hiring process. Recruiters tend to hire candidates who look and act like his or her favorite person on the planet- him or herself. Assholes will hire assholes.
  • Be like Google. Like Google, not "be" Google. They have a "Don't be evil" motto. The company works to screen them out in hiring, and nasty people suffer during performance evaluations and aren't promoted to management positions.

"The No Asshole Rule" by Robert I. Sutton is a must-read for anyone looking to make a difference in their workplace. It is a very entertaining book and quite a learning experience.

This post contains information found in:
The No Asshole Rule: Building a Civilized Workplace and Surviving One That Isn't