As an aside: In previous discussions, I've seen these patterns
somewhere (possibly on jsmentors):
( ( obj || {} ).prop1 || {} ).prop2
try { return obj.prop1.prop2; } catch(e) { return undefined; }
The first doesn't handle errors, the second might handle too
many (the second is also a statement, not an expression).
With #-functions offering a shorthand for delayed evaluation,
one might even define (with the same caveat about exceptions):
function safely(_x) { // exception-safe evaluation of delayed _x
try { return _x(); } catch(e) { return undefined; }
}
.. safely( #(){ obj.prop1.prop2 } )
As a meta point, it may be useful to consider why these operators
cannot be defined as the need for them arises. Unless the operators
are considered harmful, having to ask for a language extension
often highlights serious shortcomings in the language:
- no user-defined infix operators..
workaround: none really, though we can try to emulate
infix ops through object methods
- all functions evaluate their arguments by default,
and there isn't even a way to change this default
workaround:
e --> #(){ e } // delay evaluation of e
e --> e() // force evaluation of delayed e
This workaround has the well-known problem that
all call-sites have to be modified. A way to specify
delays on formal parameters instead would help.
Possible approximation of intended infix operator definition
(I'd be very happy to see a better approximation!):
// no 'user' defined
var user1 = {};
var user2 = { address : {} };
var user3 = { address : { street : "lonely" }};
// wrap obj to allow safe property access,
// with (_qd) and without (qd) safe delayed evaluation
function $(obj) {
return { qd : function(prop) { return (obj || {})[prop]; }
, _qd: function(prop) { try { return (obj() || {})[prop]; }
catch(e) { return undefined; }; } };
}
// who wants to code like this, even if it works?
// delay dangerous phrases, then wrap and select
log( typeof $($(#(){ user })._qd('address')).qd('street') );
// just wrap and select
log( typeof $($(user1).qd('address')).qd('street') );
log( typeof $($(user2).qd('address')).qd('street') );
log( typeof $($(user3).qd('address')).qd('street') );
Can we do any better with Harmony, without changing
the language for every useful operator? If we cannot do
better, should the language just keep growing, should
users make do without their operators, or should the
shortcomings be fixed?-)
Claus
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss