PDA

View Full Version : 183 bytes can be saved in JSON.js



papandreou
11 Nov 2009, 9:06 AM
I provided a patch for saving 183 bytes in JSON.js here: http://www.extjs.com/forum/showthread.php?p=352375#post352375

However, nobody noticed because I posted after the thread had been marked as FIXED. Mystix recommended that I start a new thread, so that's what I'm doing now :).

Best regards,
Papandreou

hendricd
11 Nov 2009, 9:30 AM
How about we actually implement the 'safe' option, too ? :-?

As proposed:


/**
* Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set.
* @param {String} json The JSON string
* @return {Object} The resulting object
*/
this.decode = function(o) {
var decoder = Ext.USE_NATIVE_JSON && nativeJSONAvailable ? JSON.parse : doDecode;

if(!!safe){
var obj = null;
try{ obj = decoder(json); } catch(je){}
finally { return obj; }
}else {
return decoder(json);
}
};
}()

or, as the current closure [SVN]:


/**
* Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set.
* @param {String} json The JSON string
* @return {Object} The resulting object
*/
this.decode = function() {
var dc;
return function(json, safe) {
if (!dc) {
// setup decoding function on first access
dc = isNative() ? JSON.parse : doDecode;
}

if(!!safe){
var obj = null;
try{ obj = dc(json); } catch(je){}
finally { return obj; }
}else {
return dc(json);
}

};
}()

papandreou
11 Nov 2009, 11:20 AM
How about we actually implement the 'safe' option, too ? :-?


Seems like a topic for a separate thread :)


if(!!safe){If your patch is accepted, I propose that we save another two bytes by omitting the two nots. Semantically the above code is exactly identical to if(safe) {... I realize why you'd sometimes want to use that trick to force a value to be converted to boolean, but here you're just asking about the truth value.

Best regards,
Papandreou

hendricd
11 Nov 2009, 11:24 AM
Agreed, dbl-negation optional. ;)

Bulle Bas
18 Nov 2009, 3:27 PM
how can
if(!!safe) be different from
if (safe) ?

I think the boolean cast will happen anyhow? No? :-|